2012-01-31 65 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