簡體   English   中英

檢索POST數據回AJAX / jQuery

[英]Retrieve POST data back AJAX / jQuery

post.js

$.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后,我無法檢索或發送數據...

我究竟做錯了什么?

我認為$ .ajax函數將更適合您的需求:

$.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所說,請提供有關錯誤原因的更多信息。

如果您正在訪問data.testId ,則意味着您正在訪問從update.php收到的響應(存儲在示例中名為data的變量中),作為jQuery post調用的結果。 通過將數據類型稱為jSon ,可以確保將服務器的響應轉換為jSon格式。

如果您的update.php頁面返回這樣的jSon

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

然后,您可以訪問單個值,例如data.iddata.age

如果您具有從服務器頁面返回的有效json,則下面的代碼應該可以正常工作

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

我會做@ 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
        }
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM