在Asp上使用Json时出错

Error while using Json on Asp

本文关键字:Json 出错 Asp      更新时间:2023-09-26

我在aspnet上使用JavaScript和C#。我想从Asp页面向后面的代码传递3个值,为此我使用Json方法。这是我的做法:

   //initialize x, y and nome
   var requestParameter = { 'xx': x, 'yy': y, 'name': nome };
            $.ajax({
                type: 'POST',
                url: 'Canvas.aspx/GetData',
                data: requestParameter,
                //contentType: "plain/text",
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                success: function (data) {
                    alert(data.x);
                },
                error: function () { alert("error"); }
            });

然后在C#上我做:

[WebMethod]
public static string GetData(Object[] output)
{
    return output.ToString();
}

出于某种原因,我不断收到警告,说"错误"(我在ajax post方法中定义的错误)。我想知道为什么,以及如何避免这种情况。提前感谢

 { 'xx': x, 'yy': y, 'name': nome }

不是有效的json。

有效的是

 var requestParameter = { "xx": 1, "yy": 11, "name": "test" }

为了运行,只需更改webmethod上的参数,并从object[]更改为Dictionary<string,object>

作为您最后一条评论的继续,我用另一个解决方案更新了我的帖子。

Aspx页面

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>

      function testmethod() 
          {
            var requestParameter = { "xx": 1, "yy": 11, "name": "adadsaasd111" };
            PageMethods.test(requestParameter);
           }
        function test() 
        {
            testmethod();
        }
    </script>
    <input id="Button1" type="button" onclick="return test();" value="button" />
</form>

cs代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    [System.Web.Services.WebMethod]
    public static void test(Dictionary<string,object> cal)
    {
       // todo 
    }
}

}

var requestParameter = { 'xx': x, 'yy': y, 'name': nome };更改为

var requestParameter = { "xx": "'+x+'", "yy": "'+y+'", "name": "'+nome+'" };

还添加

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]

[WebMethod] 之后

也在声明类之前添加

[System.Web.Script.Services.ScriptService]

该标记是允许从脚本调用web方法所必需的

你的网络服务应该是这样的

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetData(String xx, String yy, String name)
{
    return xx+yy+name;
}

和jquery

 $.ajax({
url: '/Canvas.aspx/GetData',// the path should be correct
            data: '{ "xx": "'+x+'", "yy": "'+y+'", "name": "'+nome+'" }',
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            type: 'POST',
            success: function (msg) {
                alert(msg.d);
            },
            error: function (msg) {
                //alert(msg.d);
                alert('error');
            }
        });