如何回应ajax?

时间:2012-01-23 09:11:53

标签: atk4

我有一个字段在用户输入上发出ajax请求,我想用json对象响应它。我使用jQuery函数$.getJSON和url ?page=answersearch,但它不起作用。它不是回答json类型数据,而是发送text / html类型数据。怎么做?

1 个答案:

答案 0 :(得分:2)

如果从AJAX请求中获取一串文本,无论声明的MIME类型如何,您都可以使用jQuery的$ .parseJSON函数。

$.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.
    }
});

此外,在服务器端,您可能希望设置Content-Type标头:

header('Content-Type: text/json')

然而,并非100%必要。