[英]jQuery Ajax call not returning anything
我在jQuery中有一個異步調用,其中POST請求返回一個HTTP 200,但是沒有響應文本或任何可從該端點處理的內容。
我對Localhost的原因感到困惑,因為當我使用相同的調用來輪詢JSONTest之類的服務時,我會得到一個有效的對象作為回報。
這就是使用Slim用PHP編寫的結果端點的樣子
$app->post("/search", function() use ($app) {
try {
$request = $app->request;
$body = $request->getBody();
$input = json_decode($body);
//Prepare search string
$query = "%". $input->query . "%";
$grade = '%grade ' . $input->grade . "%";
$meta = $input->meta;
$proc_results = array();
$item = new stdClass();
$item->id = 1;
$item->source = "source";
$item->type = "lesson_plan";
$item->description = "Description of the Lesson Plan";
$item->date_created = 1234567890;
$proc_results[] = $item;
$app->response()->header('Content-Type','application/json');
$app->response()->body(json_encode($proc_results));
} catch (Exception $e) {
}
});
使用POSTMAN之類的實用程序時,此調用的確返回JSON響應,但是當我使用以下測試jQuery代碼時,得到的對象沒有任何responseText或任何解釋器具有該對象的符號。
$.ajax({
"type":"POST",
"url":"http://localhost:9001/search",
"data":{"query":"math","grade":"4"}
}).done(function(result) {
console.debug(result);
});
我是否在我的done()調用中缺少用於輪詢資源的組件? 我的Slim通話是否發送格式錯誤的JSON? 如果需要,我可以在線獲取有效的演示。
類型,網址,數據不應為字符串。 嘗試不使用字符串。 它應該工作。 同樣,數據鍵也不應該是字符串。
嘗試這個
$.ajax({
type:"POST",
url:"/search",
data:{query:"math",grade:"4"}
}).done(function(result) {
console.debug(result);
});
嘗試將數據類型設置為JSON,擴展@doniyor的答案:
$.ajax({
type:"POST",
url:"/search",
datatype:"json",
data:{query:"math",grade:"4"}
}).done(function(result) {
console.debug(result);
})
參見: http : //api.jquery.com/jquery.ajax/
從您的評論看來,您正在尋找JSON結果。
我找到了根本原因:我沒有為PHP解析發送有效的JSON。 通過添加JSON.stringify,它可以按預期響應:
$.ajax({
type:"POST",
url:"http://localhost:9001/search",
dataType:"json",
contentType: "application/json",
data: JSON.stringify({"query": "math", "grade": "4", "meta": "z"})
}).done(function(result) {
console.debug(result);
});
謝謝你們的幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.