【问题标题】:What did I wrong with my Ajax code?我的 Ajax 代码有什么问题?
【发布时间】:2016-12-22 11:40:27
【问题描述】:

我想在单击按钮时在我的列表框中添加项目,然后,它必须通过ajax返回已添加到列表框中的值。

这里是代码,我试过了。

$('#right').click(function () {
    alert("Start process");
    var item = "testing";

    $.ajax({
        url: 'ReportSalesAll.aspx/setRightListBoxitems',
        method: 'post',
        ContentType: 'application/json',
        data: '{listItems:' + item + '}',
        dataType: 'json',
        success: function (data) {
           alert("result = " + data.d.text)
        },
        failure: function (response) {
           alert(response.d);
        },
        error: function (error) {
           alert("Error = "+error);
        }
    });
});

aspx代码:

<input type="button" id="right" value=">>" />

<asp:ListBox ID="lstRight" runat="server" SelectionMode="Multiple" Width="100%" Height="220"></asp:ListBox>

后端代码:

[System.Web.Services.WebMethod]
public static string setRightListBoxitems(string listItems)
{
   ReportSalesAll rs = new ReportSalesAll();
   rs.lstRight.Items[0].Text = listItems;
   rs.lstRight.Items[0].Value = "faisal "+listItems ;
   return rs.lstRight.Items[0].Text;
}

运行Error = [Object object]时出现错误

就绪状态:4, 状态:500 statusText:内部服务器错误 responseText:消息:“无效的 JSON 原语:测试。”,StackTrace“:”在 System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()

【问题讨论】:

  • 而不是alert("Error = "+error); 使用console.log("Error:", error); - 这样您就可以实际看到服务器返回的错误响应。
  • 你试过在浏览器中调试你的代码吗?这可以为您提供错误及其对象
  • @mpf82 现在我已经更新了。请检查错误
  • @NMathur 请立即查看
  • 服务器是否以有效的 JSON 响应?您在'applciation/json' 中也有错字。

标签: javascript c# jquery ajax


【解决方案1】:

"无效的 JSON 原语:测试。",StackTrace":" at ...

问题:与这部分代码有关。 data: '{listItems:' + item + '}'您没有正确构建 JSON。

以上代码将数据返回为"{listItems:testing}",这是无效的JSON。请注意,字符串testing 周围没有" ",这就是错误所说的。

解决方案:使用JSON.stringify() 而不是手动弄脏您的手。将上面的代码行替换为

data: JSON.stringify({listItems:item});

这会将数据返回为"{"listItems":"testing"}",并且它是一个有效的 JSON。

【讨论】:

  • 如你所说,我改变了。这是错误"{"Message":"Object reference not set to an instance of an object.","StackTrace":" at DevExpressDemo.ReportSalesAll.setRightListBoxitems(String listItems) in d:\\Faisal Private\\DevExpressDemo\\DevExpressDemo\\ReportSalesAll.aspx.cs:line 181","ExceptionType":"System.NullReferenceException"}"
  • @mohamedfaisal 好...现在控件命中服务器.. 已解决.. 下一个错误可能是因为这个rs.lstRight.Items[0].Text = listItems;.. 你已经初始化了rs 但不是@987654331 @在里面..你能确认一下
  • listItems 是参数。甚至我试图返回像这样return "Result working" 这样的直接字符串。还是我上面提到的同样的错误
  • @mohamedfaisal 我的意思是lstRight .... 即:rs.lstRight.. 错误也来自您的 c# 代码.. 现在 ajax 问题已修复
  • 是的,你是对的。这些行是错误的。但结果显示为result = {"d":"testing"}。我应该如何获得价值\
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-07-28
  • 1970-01-01
  • 2019-06-06
相关资源
最近更新 更多