加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – jQuery:在jquery ajax json调用中返回字符串响应

发布时间:2020-12-15 23:43:46 所属栏目:百科 来源:网络整理
导读:我使用 jquery ajax请求和json作为数据类型将json数据传递给我的通用处理程序页面GenericHandler.ashx.cs. 在我的处理程序代码中,我想以字符串格式返回html表.这是我的处理程序代码的快照 context.Response.ContentType = "text/plain"; context.Response.Wr
我使用 jquery ajax请求和json作为数据类型将json数据传递给我的通用处理程序页面GenericHandler.ashx.cs.

在我的处理程序代码中,我想以字符串格式返回html表.这是我的处理程序代码的快照

context.Response.ContentType = "text/plain";      
context.Response.Write(sResponse);

其中sResponse包含< table>< tr>< td> PropertyName< / td>< td> PropertyID< / td>< / tr>< tr>< td> abc< / td>< td&gt 1 LT; / TD>< / TR>< /表>

我的jquery代码(检查错误函数中的内联注释):

id = { 'PropertyID': id };
    $.ajax("Handlers/GenericHandler.ashx?Type=getProperties",{
        type: 'post',dataType: 'json',cache: false,contentType: "application/json",data: JSON.stringify(id),success: function (data) {
            console.log(data);            
        },error: function (xhr,status) {
            console.log(status); // Output as parseError
            console.log(xhr.responseText); // My sResponse string ! But Why Here ?
        }
    });

我的问题 :

>为什么我没有得到成功功能的回应
>这是正确的方法吗?或者我应该将html表转换为json对象然后返回它.并再次以表格格式显示它?

解决方法

您的回复无效JSON正在返回纯文本. jQuery期望响应是JSON,因为你设置了contentType:“application / json”

如果站点的其余部分使用JSON作为传输格式,则将HTML包装为JSON对象并将其返回.

在您的后端代码中,返回看起来像这样的内容

{response_html : "<table><tr><td>PropertyName</td><td>PropertyID</td></tr><tr><td>abc</td><td>1</td></tr></table>"}

在您的jQUery代码中,您可以在成功回调中访问它.

success: function (data) {
    console.log(data.response_html);            
},

注意 – 您需要从后端代码中删除纯文本内容类型并制作该JSON.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读