在Jquery AJAX请求中转义单引号

时间:2013-05-25 08:59:53

标签: javascript jquery ajax json

我正在使用JQuery AJAX将数据传递给我的服务,如果我输入带单引号的消息,它会过早地结束查询字符串,而我的AJAX请求将无效。有没有一种很好的方法来处理我的代码:

function addRow() {
        //debugger;
        var DM = $grid.pqGrid("option", "dataModel");
        var data = DM.data;

        var $frm = $("form#crud-form");
        $frm.find("input").val("");

        jqNew("#popup-dialog-crud").dialog({
            title: "Add Record", buttons: {
                Add: function () {
                    var row = [];
                    // These rows are the form rows for add/edit
                    var NotesTitle = $("#txtNoteTitle").val();
                    var NotesText = $("#txtNoteText").val();
                    var IsShared = $("#chkShare").is(':checked');
                    var UserID = $('[name*=hdnUserID]').val();
                    var ProfileType = $("[name*=hdnProfileType]").val();
                    var ParentID = $("[name*=hdnParentID]").val();
                    var ContactID;
                    var JobID


                    NotesTitle = NotesTitle.replace(/'/g, "\'")
                    alert(NotesTitle);

                    if (ProfileType == "Advertiser Profile" || ProfileType == "Agency Profile" || ProfileType == "Brand Profile") {
                        ContactID = null;
                        JobID = null;
                    }
                    else if (ProfileType == "Advertiser Contact Profile" || ProfileType == "Agency Contact Profile") {
                        ContactID = $('[name*=hdnContactID]').val();
                        JobID = $('[name*=hdnJobID]').val();
                    }

                    tempArray = [];

                    $.ajax({
                        url: "http://wks52025:82/WcfDataService.svc/AddNewNote()?$format=json",
                        data: "NoteTitle='" + NotesTitle + "'&" + "NoteText='" + NotesText + "'&" +
                              "UserID='" + UserID + "'&" + "ProfileType='" + ProfileType + "'&" +
                              "ParentID='" + ParentID + "'&" + "ContactID='" + ContactID + "'&" +
                              "JobID='" + JobID + "'&" + "IsShared='" + IsShared + "'",
                        type: "GET",
                        async: false,
                        datatype: "json",
                        success: function (data) {
                            jqNew.each(data.d, function (i, item) {
                                tempArray[0] = item.NotesID;
                                tempArray[1] = item.NotesTitle;
                                tempArray[2] = item.NoteText;
                                tempArray[3] = item.NoteUpdatedDate;
                                tempArray[4] = item.IsShared;
                                tempArray[5] = item.NameOfUser;
                            });
                        },
                        error: function (data) {
                            alert("Note not added");
                        }
                    })

                    data.push(tempArray);
                    $grid.pqGrid("refreshDataAndView");
                    jqNew(this).dialog("close");
                },
                Cancel: function () {
                    jqNew(this).dialog("close");
                }
            }
        });
    }

我的WCF方法

[WebGet]
    public IQueryable<vw_Note> AddNewNote(string NoteTitle, string NoteText, string UserID, string ProfileType, string ParentID, string ContactID, string JobID, string IsShared)
    {
        // Make NULL to remove compile errors
        int? IParentID = null;
        int? IContactID = null;
        int? IJobID = null;

        //Assign Variables based on ProfileType
        switch (ProfileType)
        {
            case "Advertiser Profile":
                IParentID = Convert.ToInt16(ParentID);
                IContactID = null;
                IJobID = null;
                break;
            case "Agency Profile":
                IParentID = Convert.ToInt16(ParentID);
                IContactID = null;
                IJobID = null;
                break;
            case "Brand Profile":
                IParentID = Convert.ToInt16(ParentID);
                IContactID = null;
                IJobID = null;
                break;
            case "Advertiser Contact Profile":
                IParentID = Convert.ToInt16(ParentID);
                IContactID = Convert.ToInt16(ContactID);
                IJobID = Convert.ToInt16(JobID);
                break;
            case "Agency Contact Profile":
                IParentID = Convert.ToInt16(ParentID);
                IContactID = Convert.ToInt16(ContactID);
                IJobID = Convert.ToInt16(JobID);
                break;
        }

        Guid GUserID = Guid.Parse(UserID);
        Guid NoteID = Guid.NewGuid();
        bool BIsShared = Convert.ToBoolean(IsShared);

        tblNote N = new tblNote
        {
            NotesID = NoteID,
            NotesTitle = NoteTitle,
            NotesText = NoteText,
            ParentID = IParentID,
            ContactID = IContactID,
            JobID = IJobID,
            UserID = GUserID,
            GroupID = null, // Trigger in SQL for this value
            RelatedType = ProfileType,
            IsShared = BIsShared,
            NoteCreatedDate = DateTime.Now,
            NoteUpdatedDate = DateTime.Now
        };
        try
        {
            this.CurrentDataSource.tblNotes.Add(N);
            this.CurrentDataSource.SaveChanges();
            return GetNoteByID(NoteID);

        }
        catch (Exception ex)
        {
            return GetNoteByID(NoteID);
        }
    }

这是我得到的JSON响应:

{"error":{"code":"","message":{"lang":"en-GB","value":"Bad Request - Error in query syntax."}}}

1 个答案:

答案 0 :(得分:3)

您不应该自己构建URL参数部分,而是让jQuery进行编码。

使用

$.ajax({
    url: "http://wks52025:82/WcfDataService.svc/AddNewNote()",
    data : {
        format:'json',
        NoteTitle:NotesTitle,
        NoteText:NotesText
        ...
    }