2012-01-31 66 views
2

我试图在$ .post函数内使用$ .getJSON,并在文本框(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?

回答

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 

顺便说一句:您的代码很容易受到SQL注入。

+0

该死的,这正是我写的。我总是喜欢只使用[ajax基础对象](http://api.jquery.com/jQuery.ajax/),以便我可以轻松地看到发生了什么或稍后再进行更改。 – ianbarker 2012-01-31 14:19:27