2012-04-15 56 views
-1

post.js检索POST数据备份AJAX/jQuery的

$.post(
    "/scripts/update.php", 
    {id: testId, age: testAge}, 
    function(data) { 
    $(".testDiv").html(data.testId); 
    $(".testDiv2").html(data.testAge); 
    }, 
    "json" 
); 

update.php

$userId = $_POST["id"]; 
$userAge = $_POST["age"]; 

// contact database and retrieve user Id and user name... 

echo json_encode(array("testId"=>$userId, "testAge"=>$userAge)); 

我如果我拿出, "json");代码,我可以将信息传递给update.php得很好,但不能检索任何数据。添加json后,我无法检索或发送数据...

我在做什么错?

+0

data.testId&data.testAge不从update.php回到那里各自的值 – 2012-04-15 13:54:11

回答

0

如果您访问的是data.testId,那意味着您正在访问从update.php收到的响应(存储在您的示例中称为data的变量中),作为jQuery post调用的结果。通过提及数据类型为jSon,您确定服务器的响应将被转换为jSon格式。

如果您update.php页面返回一个JSON这样

{ "id": "3","age":"53"} 

然后你就可以访问诸如data.iddata.age的indidual值。

,如果你有一个有效的JSON从服务器返回页面像上面

$.post("/scripts/update.php", { id: testId, age: testAge}, dataType:"json",function(data) { 
    $(.testDiv).html(data.id); 
}); 
3

我觉得$就功能会更适合您的需求在下面的代码应该工作:

$.ajax({ 
    type: "POST", 
    url: "/scripts/update.php", 
    data: {id: testId, age: testAge}, 
    dataType: "json", 
    success: function(data) { 
     $(".testDiv").html(data['testId']); 
     $(".testDiv2").html(data['testAge']); 
    } 
}); 

你的PHP脚本将保持不变。我提供的代码是由于您收到的错误信息很少。正如camus所说,请提供有关错误的更多信息。

0

我会做什么@ gimg1说,但像这样的:

var form_data = { 
      testId: $("#testIdForm").val(), 
      testAge: $("#testAgeForm").val() 
     }; 
$.ajax({ 
    type: "POST", 
    url: "/scripts/update.php", 
    data: {id: testId, age: testAge}, 
    dataType: form_data, 
    success: function(response) { 
     if(response == 'success'){ 
      //do success function here 
     } 
    } 
});