1. 程式人生 > >使用ajax傳送post請求後呼叫servlet成功前臺沒有呼叫success

使用ajax傳送post請求後呼叫servlet成功前臺沒有呼叫success

使用jquery ajax傳送請求後,前臺success方法一直沒有呼叫。

經除錯,返回狀態碼200說明請求傳送成功,後臺執行OK,猜測問題應該在前臺解析返回值部分。

錯誤示例:

function validateName() {
var name = $("#nameInputId").val();
$.ajax({
type:"POST",
url:"JsonReturnClient",
data:"name",
dataType: "json",
success:callback
});
}
function callback(result,readystatus){
alert("呼叫成功");
}

servlet:

OutputStream out = response.getOutputStream();
request.getParameter("");
String json = "{'name':'jyf'}";
out.write(json.getBytes());


然後補充error流程,除錯發現呼叫servlet成功後解析結果報錯parsererror,經查詢,前臺設定dataType為json,希望後臺返回的格式是json,如果格式不正確會出現該錯。檢查發現手寫json key、value不能用單引號結束,需要用雙引號轉義。修改後臺生成json的方法。


OutputStream out = response.getOutputStream();
request.getParameter("");
String json = "{\"name\":\"jyf\"}";
out.write(json.getBytes());

同時前臺為了方便除錯跟蹤執行結果,需要補全error分支