Ajax,PHP – 从数据库中获取
我在收集从数据库中获取的数据时遇到了一些问题。 不知道如何继续。
到目前为止我做了什么:
JQ:
$(document).ready(function(){ $('#submit').click(function(){ var white = $('#white').val(); $.ajax({ type:"POST", url:"page.php", data:{white:white} }); }); });
PHP(请求的page.php)到目前为止:
$thing = mysql_real_escape_string($_POST["white"]); ..database connect stuff.. $query = "SELECT * FROM table1 WHERE parameter='$thing'"; if($row = mysql_query($query)) { while (mysql_fetch_array($row)) { $data[]=$row['data']; } }
我不知道的是,如何发送数据并使用ajax接收它。
请求不成功时错误怎么办?
对数据库注入的ajax调用有多安全?
谢谢 :)
您需要$.ajax()
的success
参数才能$.ajax()
调用后获得响应
$('#submit').click(function(){ var white = $('#white').val(); if(white == '') { // display validation message } else { $.ajax({ type:"POST", url:"page.php", data:{"white":white} success:function(data){ $('#someID').html(data); } }); });
无论你在page.php
回应什么(HTML标签或变量)都将显示在ID为someID
的元素中,最好保持元素为
在page.php
,您可以使用$_POST['white']
捕获输入元素中输入的值,并使用它来执行您想要的任何数据库操作
To send out data to you can write following line at the end : echo json_encode($data);exit; To receive response and errors when request is not successful in ajax : jQuery.ajax({ type:"POST", url:"page.php", data:{white:white}, asyn: false, success : function(msg){ var properties = eval('(' + msg + ')'); for (i=0; i < properties.length; i++) { alert(properties[i]); } }, error:function (XMLHttpRequest, textStatus, errorThrown) { alert(textStatus); }
For Feeling more safety do the following things: 1. Open a Session. 2. Detect Referrer. 3. Use PDO Object instead mysql_real_escape_string 4. Detect Ajax call : if(empty($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !='xmlhttprequest') { //Is Not Ajax Call! }