[英]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.