簡體   English   中英

jQuery發布並獲取

[英]JQuery Post And Get

我正在嘗試編寫一種方法,該方法可以將數據發布到php文件中,並獲取結果並以變量形式返回輸出。 由於某種原因,我的代碼塊無法正常工作。

function post_get(){

var result = null;

$.post("modules/data.php", { "func": "getNameAndTime" },
function(data){
    result = JSON.parse(data);
}, "json");


return result;
}

使用此方法時出現此錯誤

SyntaxError:JSON解析錯誤:意外的標識符“未定義”

  1. Ajax是異步的。
  2. 您的PHP返回有效的JSON嗎?

這就是應該利用Ajax的異步特性編寫代碼的方式。

function post_get(){

    return $.post("modules/data.php", { "func": "getNameAndTime" }, "json");

}

post_get().done(function(data){
    // do stuff with data
    console.log(data);
}).fail(function(){
    console.log(arguments);
    alert("FAIL.\nCheck the console.");
});
// Do not attempt to bring data from inside the above function to out here. 

如果您的服務器返回正確的JSON編碼輸出並設置了正確的標頭( Content-Type: application/json ),則可以立即使用data

$.post("modules/data.php", {
    "func": "getNameAndTime"
},
function(data){
    console.log(data);
}, "json");

// btw, at this point in the code you won't have access to the return value

實際上,即使沒有返回正確的數據, console.log(data)應為您提供足夠的信息,以弄清其為什么不能正常工作。

暫無
暫無

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

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