I've got field which makes ajax request on user input, and I want to response to it with json object. I use jQuery function $.getJSON
with url ?page=answersearch
, but it doesn't work. Instead of answering with json type data, it sends text/html type data. How to do it?
If you are getting a string of text back from an AJAX request, regardless of the declared MIME-type, you may make use of jQuery's $.parseJSON function.
$.ajax({
url: '/someurl',
type: 'get',
data: {
page: 'answersearch'
},
success: function(rsp) {
if (typeof rsp === 'string') {
rsp = $.parseJSON(rsp);
}
// rsp has been changed from a string into an object.
}
});
Also, on the server side, you may wish to set the Content-Type header:
header('Content-Type: text/json')
It's not 100% necessary, however.