首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在使用ajax post响应时出现错误块

在使用ajax post响应时出现错误块
EN

Stack Overflow用户
提问于 2018-02-20 20:58:18
回答 1查看 37关注 0票数 0

当发送ajax post请求时,数据将提供服务,而从响应中返回时,数据将进入上述错误函数,有人能在这方面帮助我吗

代码语言:javascript
运行
复制
<!-- language: lang-js -->

$.ajax({
    type: "POST",
    url: serviceUrl,
    data: stringData,
    contentType: "application/json",
    dataType: "text", // the data type we want back, so text.  The data will come wrapped in xml
    success: function(response) {
        alert("successs :::::::::::::::" + $("#searchresultsA").html(data)); // show the string that was returned, this will be the data inside the xml wrapper
        return response;
    },
    error: function(response) {
        alert("error ::::::::::::" + response.responseText); // show the data inside the xml wrapper
        return response.responseText;
    },
    failure: function(response) {
        alert("failure ::::::::::::" + response);
        return response;
        }
   });
}
EN

回答 1

Stack Overflow用户

发布于 2018-02-20 21:37:40

您应该在AngularJS中使用$http而不是$.ajax。您正在寻找关于AJAX响应为什么会出现错误的解决方案,而from you previous question,很明显,您需要知道如何正确地对数据进行解析

以前使用的$http (比$.ajax更好)期望您的数据以 JSON 的形式到达,但是您的后端将其作为纯文本发送,从而给您一个JSON解析器错误。您需要指定如何发送此信息,以及是否将其编码为JSON。

对于PHP

有一个函数json_encode()可以用来将对象/数组返回为JSON。在您的示例中尝试以下代码:

代码语言:javascript
运行
复制
echo json_encode( $json );

验证您的响应

考虑使用console.log(response); (在异步回调中)检查从后端接收到的内容。例如:

代码语言:javascript
运行
复制
$http.post(url, stringData).
then((response)=>{
    console.log(response);
},(error)=>{
    console.log(error);
}); 
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48885838

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档