使用$ .post()将值发布到PHP并使用$ .getJSON返回

时间:2012-01-31 14:09:32

标签: php jquery

我正在尝试在$ .post函数中使用$ .getJSON并在textbox(id = desc)中显示返回值。 这是我的代码:

function dataload(){
    var currentId = $(this).attr('id'); 
    var e = document.getElementById(""+currentId);
    var sel = e.options[e.selectedIndex].text; 
    $("#"+currentId).change(function (){
        $.post("test.php", {data:sel}, function(data){
            $.getJSON("test.php", function(data){
                $("#desc").val(data[0].description);
            });
        });
    });
}

test.php的:

<?php
   include('config.php');//db connection
   $itemvalue=($_POST["data"]);
   $item = mysql_query("SELECT description FROM invoice WHERE item='$itemvalue'");
   $data = array();
   while($row = mysql_fetch_array($item, true)) {
        $data[] = $row;
   }
   $data = json_encode($data);
   echo $data;
?>

但是test.php没有采用发布值。那么如何发布sel?

1 个答案:

答案 0 :(得分:4)

您使用test.php拨打$.post两次,使用$.getJSON拨打一次。在第一次调用时,POST参数应该正确传递给您的PHP - 但您不会对请求的结果执行任何操作。在第二次调用时,您不传输任何POST参数,$itemvalue只是空。

只需使用:

$.getJSON("test.php", {data:sel}, function(data){
    // [...]

并在你的PHP中:

$itemvalue=$_GET["data"]; // $.getJSON performs a GET request

btw:您的代码很容易受到SQL注入攻击。