簡體   English   中英

如何解決Ajax上的無效JSON基本錯誤?

[英]How to solve Invalid JSON Primitive error on Ajax?

我正在嘗試使用Asp.net上的webmethod執行ajax,

我正在使用JQuery-3.1.1

我想將值傳遞給服務器並取回值。 我不知道我做錯了什么。

ASP.NET代碼

<div class="row">
   <asp:Button ID="btnSave" runat="server" CssClass="btn btn-info"  Text="save" />
</div>

jQuery代碼

$(document).ready(function () {
    $('#btnSave').click(function () {
        var name= 'xxx';

        $.ajax({
            type: "POST",
            url: "AjaxWebMethod.aspx/getFileExistOrNot",
            data: '{fileName:'+name+'}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess,
            failure: function (response) {
                alert("failed ="+response.d);
            },
            error: function (response) {
                alert("error ="+response.d);  //This alert is executing
            }
        });

        function OnSuccess(response) {
            alert("Result ="+response.d.mydata);
        }
        return false;
    });
});

C#代碼

public partial class AjaxWebMethod : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    [WebMethod]
    public static string getFileExistOrNot(string fileName)
    {
        string mydata="ajaxworking";
        return mydata;
    }
}

我真的不知道我在哪里犯錯了

控制台上的錯誤消息

{消息:“無效的JSON原語:xxx。”,…}

ExceptionType: “System.ArgumentException”

消息:“無效的JSON原語:xxx。”

您能以適當的理由給出解決方案嗎? 這將有助於我了解更多,謝謝

您的postData是無效的JSON,字符串中需要用引號引起來:

'{fileName:'+name+'}'

它應該是:

 '{fileName:"'+name+'"}'

您正在進行的jQuery調用已設置為在響應中使用JSON格式。 看來您的服務器端代碼只是返回了未編碼為JSON的字符串。 您要么需要更改服務器的輸出,要么需要更改ajax調用的期望。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM