[英]Error while using Json on Asp
我在ASPNET上使用JavaScript和C#。 我想将3个值从Asp页面传递到后面的代码,并且这样做是使用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');
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.