我有以下JSON:Parseerror使用JSON和jQuery
[{"label":"75001","value":"75001"},
{"label":"75002","value":"75002"},
{"label":"75003","value":"75003"},
{"label":"75004","value":"75004"},
{"label":"75005","value":"75005"},
{"label":"75006","value":"75006"},
{"label":"75007","value":"75007"},
{"label":"75008","value":"75008"},
{"label":"75009","value":"75009"}]
它會導致JQuery的一個parseerror。
我實際使用的jquery.ui自動完成控制如下:
jQuery(document).ready(function() {
jQuery("#accountPostcode").autocomplete({
source : function(request, response) {
var jqxhr = jQuery.ajax({
url : "utils/JSonPostcodesWithQueryParam",
dataType : "json"
}).fail(function() {
console.log("error:");
console.log(jqxhr.statusText);
});
},
minLength : 2
});
});
我不知道我收到錯了,因爲我的Json似乎是正確的......
任何人有任何線索?
編輯:
這裏是產生JSON:
package com.bignibou.web.pages.utils;
import java.util.List;
import org.apache.tapestry5.EventConstants;
import org.apache.tapestry5.StreamResponse;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.RequestParameter;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.util.TextStreamResponse;
import com.bignibou.domain.utils.PostcodeJson;
import com.bignibou.service.AccountService;
import com.google.gson.Gson;
public class JSonPostcodesWithQueryParam {
@Inject
private AccountService service;
@OnEvent(EventConstants.ACTIVATE)
StreamResponse loadPostcodes(@RequestParameter(value = "term") String beginningOfPostcode) {
Gson gson = new Gson();
List<PostcodeJson> postcodes = service.loadPostcodes(beginningOfPostcode);
return new TextStreamResponse("application/json","UTF-8", gson.toJson(postcodes));
}
}
Darin。非常感謝演示。我使用Chrome的網絡工具發現問題。內容類型設置爲「text/html」。這很奇怪,因爲我確實指定了'TextStreamResponse(「application/json」,「UTF-8」,gson.toJson(postcodes)); ' – balteo 2012-01-28 14:57:36
@balteo,迴應內容如何?它實際上是JSON嗎?我懷疑服務器將它設置爲text/html,因爲服務器出現錯誤,並且它顯示了一個錯誤頁面。你設置'dataType:'json''這一事實意味着jQuery忽略了服務器的Content-Type頭並假定了JSON。但是如果服務器在響應中沒有發送正確的JSON,它將無法工作。所以修復你的服務器端代碼。 – 2012-01-28 14:59:17
發現問題!這是由於一個錯誤指定的url:'url:'utils/JSonPostcodesWithQueryParam','我的部分基本錯誤!謝謝!它實際上解決了我的應用程序的主頁... – balteo 2012-01-28 15:01:12