I have the following Json:
[{"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"}]
It causes a parseerror in JQuery.
I actually use the jquery.ui autocomplete control as follows:
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
});
});
I am not sure what I am getting wrong as my Json seems correct...
Any one has any clue?
EDIT:
Here is what generates the 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));
}
}
Can't see anything wrong with your code other the fact that you never do anything with the results of your AJAX call. Here's a full working demo. I suspect that your server might somehow not return correct JSON which is the most likely cause of the error. You should make absolutely sure that the server responds with status code 200, sets Content-Type
header to application/json
and sends the exact JSON in the response body. Use FireBug or similar tool to analyse what exactly is sent over the wire during this AJAX request.
Also you don't seem to ever be sending the term request parameter. Try like this:
jQuery('#accountPostcode').autocomplete({
source : function(request, response) {
var jqxhr = jQuery.ajax({
url : 'utils/JSonPostcodesWithQueryParam',
data: { term: request.term },
dataType : 'json'
}).fail(function() {
console.log('error:');
console.log(jqxhr.statusText);
}).success(function(data) {
response(data);
});
},
minLength : 2
});