Hey, under this url 1234/?fmt=json I create a json object like that
SurveyJson = {question:$("#question").val(),choice:Choice,count:Count};
var jsonString = JSON.stringify(SurveyJson);
and I am trying to retrieve the json object through a AJAX call
var url = "1234?fmt=json";
$.ajax({
url: url,
type: "get",
dataType: 'json',
success: function (data) {
$("#display").html(data);
}
});
How c开发者_如何学Goome I cant display the data? I have tried that if I cross out the dataType parameter and keep others the same, I can get the json string somehow, which I dont know why. And I couldnt help but noticed that some people who have the similar problem put "post" as type instead of "get", why is that if that is correct? thank you
Make sure your "callback url" 1234/?fmt=json only returns json
for example try hard coding values and see if it works, change the code at that url to output this as your http response and remove the other stuff. just respond with exactly whats shown on this line and nothing else.
{question:"my question",choice:"a choice",count:3}
Change your calling code to:
var url = "1234?fmt=json";
$.ajax({
url: url,
success: function (data) {
alert(data);
alert(data.question);
}
});
If you see two alert boxes; the first one with a contents of "[Object object]" (this varies slightly depending on browser) and a second alert with "my question" then you are off to a good start. Post back and let me know and we'll take it from there.
Also, setting the "type" attribute to "get" or "post" makes no difference in regards to parsing the response text of your http request to 1234/?fmt=json, into a valid json object in the browser. Get and Post have important differences but nothing relevant to parsing the response text of your http request.
If you remove the dataType then by default it will return as html (which will be one long string). I recommend outputting the data as a string (by making the dataType 'html' or removing it), and using this JSON validator to make sure the problem isn't there.
GET and GET define the method of the request. GET will take advantage of the query string (url). You want to use GET, based on your example url. Change your ajax call to this
$.ajax({
url: '1234',
type: "get",
data: { 'fmt': 'json' },
dataType: 'json',
success: function (data) {
$("#display").html(data);
}
});
精彩评论