在Asp上使用Json时出错
Error while using Json on Asp
我在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');
}
});
相关文章:
- 解析JSON并从中删除对象会出错
- 加载db.json时出错
- 解析将数据从 JSON 发送到 Django 时出错
- 使用 RESTful API,如果未定义特定的响应 json 级别,我如何在客户端不出错
- 从静态文件加载json时出错
- 解析从js发送到Java的json字符串时出错
- JSON.parse在循环对象上未出错
- 将JSON映射到observableArray时出错
- 406向Spring Controller发送JSON时出错
- 在NodeJS中编辑JSON数据时出错
- 尝试从JSON加载单词时出错
- 使用JQuery和JSON将对象发送到JAX-RS时出错
- 在变量中存储 JSON 数据时出错
- 从标记内容解析 JSON 时出错
- 从 JavaScript 中的本地 JSON 文件读取时出错
- 转换为 JSON 的 XML 节点会出错
- Newtonsoft Json.net 解析布尔值时出错
- 405 AJAX 调用 JSON 时出错(xhr.status)
- 从http客户端检索json出错
- 从包含字母数字的命名空间读取JSON出错