Javascript 从AJAX命令返回JSON响应

Javascript 从AJAX命令返回JSON响应,javascript,jquery,ajax,response,Javascript,Jquery,Ajax,Response,如何让本机javascript AJAX以JSON格式返回响应,而不是“HTML上的文本” 说明: 在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 = { d

如何让本机javascript AJAX以JSON格式返回响应,而不是“HTML上的文本”

说明: 在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);
  }
现在,代码被更改为本机javascript AJAX,在其中我制作了一个“application/json;charset=UTF-8’请求,我将以‘text over HTML’而不是JSON返回响应

本机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
请注意“内容长度”值为1063。我不确定这是否是问题所在。
那么,重复一下,我如何让本机javascript AJAX以JSON而不是“HTML上的文本”返回响应?

一旦从服务器接收到JSON文本,您可以始终执行以下操作:

var jsonStr = "<<your_json_string_response>>";
var jsonObject = eval('('+jsonStr+')');
var jsonStr=”“;
var jsonObject=eval(“(“+jsonStr+”)”);

如果您的响应是有效的JSON,请尝试以下操作:

xmlhttp.onreadystatechange = function () {
    if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
        var jsonResponse = JSON.parse(xmlhttp.responseText);

        console.log(jsonResponse);
    }
}

您可以尝试
responseType

xmlhttp.responseType = 'json'
但首先检查浏览器支持


您没有请求相同的URL。这可能是问题所在吗?@cellik,不,我更改了链接以进行编辑。URL对于jquery&native js代码是一样的。我不确定你的意思,你只需要得到一个文本,你需要用类似的东西来解析它。如果设置了数据类型,JQuery会自动执行此操作