Как я могу получить собственный javascript AJAX для ответа в JSON, а не на текст через HTML?Возвращаемый ответ в JSON от команды AJAX
Описание: В jquery следующая функция AJAX возвращает данные JSON, что нам и нужно.
Jquery КОД
//ajax Handler function through which I set default attribute and send request function defined separately to send request to server
ajaxHandler = {
defaultAttributes: {
type: 'GET',
url: 'index.php/request',
datatype: 'json',
data: {},
success: null,
error: function(data) {
errorHandler.showError('An Error occurred while trying to retreive your requested data, Please try again...');
},
timeout: function() {
errorHandler.showError('The request has been timed out, Please check your Internet connection and try again...');
}
},
sendRequest: function(attributes) {
//i perform here through jquery
$.ajax(attributes);
}
Теперь, что код будет изменен на родной яваскрипт AJAX, в котором я делаю 'приложение/JSON; Charset = UTF-8' запрос, я набираюсь ответ обратно в «текст поверх HTML» вместо JSON.
NATIVE JAVASCRIPT
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
attributes.success(attributes.data);
}
}
xmlhttp.open(attributes.type, attributes.url);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send((attributes.data));
Сравнивая два в Chrome Инструменты разработчика, расположенную на вкладке Сеть, вот что я получаю за JQuery AJAX:
Remote Address:127.0.0.1:80
Request URL:http://localhost/1412-DressingAphrodite/Webapp/index.php/request/getallfeatures
Request Method:GET
Status Code:200 OK
Request Headersview source
Accept:/
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-GB,en-US;q=0.8,en;q=0.6
Cache-Control:no-cache
Connection:keep-alive
Cookie:PHPSESSID=tivt0hi9oqtbtjem7m9d0emhr1
Host:localhost
Pragma:no-cache
Referer:http://localhost/1412-DressingAphrodite/Webapp/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/39.0.2171.65 Chrome/39.0.2171.65 Safari/537.36
X-Requested-With:XMLHttpRequest
Response Headersview source
Connection:Keep-Alive
Content-Type:application/json; charset="UTF-8"
Date:Fri, 30 Jan 2015 04:43:07 GMT
Keep-Alive:timeout=5, max=18
Server:Apache/2.4.10 (Ubuntu)
Transfer-Encoding:chunked
X-Powered-By:PHP/5.5.12-2ubuntu4.1
И вот что я получаю в Родной Javscript AJAX:
Remote Address: 127.0.0.1:80
Request URL: http://localhost/1412-Dre/Webapp/index.php/request/getallfeatures
Request Method: GET
Status Code: 403 Forbidden
Request Headersview source
Accept:/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-GB,en-US;q=0.8,en;q=0.6
Cache-Control: no-cache
Connection: keep-alive
Content-Type: application/json;charset=UTF-8
Cookie: PHPSESSID=tivt0hi9oqtbtjem7m9d0emhr1
Host: localhost
Pragma: no-cache
Referer: http://localhost/1412-Dre/Webapp/ User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/39.0.2171.65 Chrome/39.0.2171.65 Safari/537.36
Response Headersview source
Connection: Keep-Alive
Content-Length: 1063
Content-Type: text/html
Date: Fri, 30 Jan 2015 06:40:26 GMT
Keep-Alive: timeout=5, max=90
Server: Apache/2.4.10 (Ubuntu)
X-Powered-By: PHP/5.5.12-2ubuntu4.1
Примечание: ntent-Length 'значение 1063. Я не уверен, что проблема. Итак, чтобы повторить, как я могу получить собственный javascript AJAX для ответа в JSON, а не на текст поверх HTML?
Вы не ищите тот же URL-адрес. Возможно, это проблема? – cellik
@cellik, нет, я изменил ссылку для редактирования. URL-адрес для jquery и собственного js-кода. – Kayote
Я не уверен, что вы имеете в виду, вы просто получите текст, который вам нужно проанализировать с помощью чего-то вроде ['JSON.parse'] (https://developer.mozilla.org/en/docs/Web/JavaScript/ Справка/Global_Objects/JSON/синтаксический анализ). JQuery делает это автоматически, если вы задаете тип данных – Spokey