JQuery Post和Get

Yus*_*Ali 0 javascript php jquery

我有一个我正在尝试编写的方法,可以将数据发布到php文件并获取结果并在变量中返回输出.出于某种原因,我的代码块无效.

function post_get(){

var result = null;

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


return result;
}
Run Code Online (Sandbox Code Playgroud)

使用此方法时出现此错误

SyntaxError:JSON解析错误:意外的标识符"undefined"

use*_*654 7

  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. 
Run Code Online (Sandbox Code Playgroud)