发送ajax请求ASP.NET

时间:2015-08-12 08:42:12

标签: javascript jquery asp.net ajax

我是ajax请求和asp.net世界的新手。我试图向aspx页面发送ajax请求。当我调试服务器端时似乎没问题,但响应打印错误消息? 我试图更改Response.ContentType但它没有解决我的问题。有什么建议吗?

这是我的javascript代码:

            function onclick(){
             $.ajax({
                url: "SandaAJAXRequests.aspx",
                type: "post",
                data: JSON.stringify({ "first": "getevent","second":"data" }),
                dataType: 'json',
                success:
            function (response)
            {
                roundNumber = 1;
                numberofblackwins = 0;
                numberofredwins = 0;
                ifBattleIsOver = false;
                $("#round").text(roundNumber);
                var result = response.split(",");
                name1 = result[1];
                name2 = result[2];

                var r = confirm("Is " + name1 + " the black competitor?");
                if (r == true) {
                    $("#black_competitor_name").text(name1);
                    $("#red_competitor_name").text(name2);
                }
                else {
                    $("#black_competitor_name").text(name2);
                    $("#red_competitor_name").text(name1);
                }
            },
                error: function (xhr) {
                    alert("Problem sending data to the server");
                }
            });
        }

这是我的服务器端:

protected void Page_Load(object sender, EventArgs e)
    {
        string jsonString = String.Empty;
        Request.InputStream.Position = 0;
        using (var inputStream = new StreamReader(Request.InputStream))
        {
            jsonString = inputStream.ReadToEnd();
        }
        string data = jsonString.Replace("\\", "");
        char[] seperators = { ':', ',', '"' };
        string[] a = data.Split(seperators);
        string t = a[4];
        JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
        object serJsonDetails = javaScriptSerializer.Deserialize(jsonString, typeof(object));
        string requestType = serJsonDetails.ToString();
        switch (t)
        {
            case "getevent":
                SandaEvent current = (SandaEvent)Application["CurrentEvent"];
                Response.ContentType = "text/plain";
                String response = current.id + "," + current.name1 + "," + current.name2;
                Response.Write(response);
                Response.End();
                break;
    }}

1 个答案:

答案 0 :(得分:0)

myObject["createdAt"] as! NSDate;

中缺少contentType
$.ajax({})
当你使用$ .ajax({})

做帖子时,

是必要的

Content-type: application/json; charset=utf-8 将内容指定为JSON格式,以UTF-8字符编码进行编码。