2012-08-01 164 views
0

我在收集从数据库中获取的数据时遇到了一些问题。不知道如何继续。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调用数据库注入有多安全?

谢谢:)

+0

关于安全的事情 - 为您做出处理它的脚本将它作为安全。 – Fluffeh 2012-08-01 11:32:40

+1

我看到你正在使用mysql_real_escape字符串。在手册页(http://php.net/mysql_real_escape_string)中,您可以看到两件事:1)建议切换到PDO(或mysqli)2)在调用它之前,应该连接到数据库 – mishu 2012-08-01 11:36:04

+1

I'对不起,但回答这个问题需要编写一个关于基本jQuery/ajax/php用法的教程,我怀疑有人会愿意这样做,并且网络上有足够的人。我可以给你一些提示,但看看:(JQ :)'.get()','$ .post()'; (PHP :)'json_encode()' – MiDo 2012-08-01 11:36:07

回答

7

你需要在一个$.ajax()参数success得到一次呼叫时

$('#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,优选保持元件的<div>

page.php的元件,可以捕获在输入输入的数值元素使用$_POST['white'],并用它做任何你想要的DB行动

0
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); 
    } 
0
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! 
    }