Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/379.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用json/ajax发送到webmethod的字符串_C#_Javascript_Asp.net - Fatal编程技术网

C# 使用json/ajax发送到webmethod的字符串

C# 使用json/ajax发送到webmethod的字符串,c#,javascript,asp.net,C#,Javascript,Asp.net,我有一个ajax调用,从aspx页面向webmethod(c#)发送一些数据,其中一个参数是一些自由文本注释。现在我注意到一些错误,数据库没有更新。因此,通过一些检查,我相信它的斜杠和’s以及其他可能的角色造成了这种情况。我尝试使用escape()方法,但它可以工作,但随后会向数据库中添加我不需要的各种编码文本。我不是一个非常有经验的程序员,所以我知道这里有一些编码要做,但我不确定如何。下面是ajax,在我得到斜杠和 $("#btnEditFields").click(function () {

我有一个ajax调用,从aspx页面向webmethod(c#)发送一些数据,其中一个参数是一些自由文本注释。现在我注意到一些错误,数据库没有更新。因此,通过一些检查,我相信它的斜杠和’s以及其他可能的角色造成了这种情况。我尝试使用escape()方法,但它可以工作,但随后会向数据库中添加我不需要的各种编码文本。我不是一个非常有经验的程序员,所以我知道这里有一些编码要做,但我不确定如何。下面是ajax,在我得到斜杠和

$("#btnEditFields").click(function () {
    //Store the New comment
    var strSupplierOrderNo = $("#<%=tbPopUpEditSuppOrdNo.ClientID%>").val();
    var strComment = $("#<%=tbPopUpEditComments.ClientID%>").val();
    var strCurrentStage = $("#<%=ddlPopUpEditCurrentStage.ClientID%>").val();
    var strReviewDate = $("#<%=tbPopUpEditReviewDate.ClientID%>").val();
    var strOrderDate = $("#<%=tbPopUpEditOrderDate.ClientID%>").val();
    var strRequiredLive = $("#<%=tbPopUpEditRequiredLiveDate.ClientID%>").val();
    var strActualAppointmentDate = $("#<%=tbPopUpEditActualAppointmentDate.ClientID%>").val();
    var strOtherRef = $("#<%=tbPopUpFieldOtherRef.ClientID%>").val();
    var EditRecordArgs = (strServiceID + "," + strSupplierOrderNo + "," + strComment + "," + strCurrentStage + "," + strReviewDate + "," + strOrderDate + "," + strRequiredLive + "," + strActualAppointmentDate + "," + strOtherRef);
    //alert(addNewCommentArgs);
    // Confirming the operation from the user
    if (confirm("You are about to add a new comment to order " + strPSTNNum + "?")) {
        $.ajax({
            type: "POST",
            //UpdateRecordInGridViewUsingAjax.aspx is the page name and UpdateOrder 
            // is the server side web method which actually does the updation
            url: "PSTN_OrderManagementTracker.aspx/updatePSTNDataInDB",
            //Passing the record id and data to be updated which is in the variable update_data
            data: "{'args': '" + EditRecordArgs + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            //Giving message to user on successful updation
            success: function () {
                alert("Comment successfully added!!!");
                location.reload(); 
            },
            error: function(xhr, ajaxOptions, thrownError){
            alert(thrownError);
        }
        });
    }
    return false;
});
});

刚刚完成,当我试图在WROLD的中间添加撇号时,我从Fixbug中犯了一个错误:

传入的对象无效,应为“:”或“}”。(50):{args': '158581,aaa5-5-23264304431 ,AAAA客户%20到%20未准备好%20作为%20民事%20工作%20已经%20到%20未%20已经完成%20%26%20当前%20有%20到%20还没有%27t%20已经%20任何%20管道/电缆/dp%20安装%2C%20作为%20确认%20与%20现场%20联系人%20技术人员%20威廉姆斯%20谁%20不知道%20此%20约会。%20还有%20此%20引用的%20管道/电缆/dp%20将%2020不正确的%20dp%20as%20%20dp%20as%20的%20地址%20是%20an%20ext%u2019l%20block%20at%2015%20Seel%20street%20%26%20premier%20inn%20is%20a%20a%20brand%20new%20hotel%20just%20正在%20完工。%0A%20范围%20项目%20团队%20%20通知%20他们%20%20%20%20延误的原因%20%20a%0A%0CYB07%2027/2012%3A00%CI00%ls,2013年5月22日,2013年5月22日,2013年5月22日,2013年5月22日,aaaa'}” StackTrace“在 System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeDictionary(Int32 深度)在 System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 深度)在 System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(字符串 输入,Int32 depthLimit,JavaScriptSerializer序列化程序),位于 System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer 序列化程序,字符串输入,类型,Int32 depthLimit)位于 System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](字符串 输入)在 System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext 上下文,JavaScriptSerializer(序列化程序)位于 System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData,HttpContext)位于 System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext 上下文,WebServiceMethodData methodData)“异常类型 “System.ArgumentException”


使用System.Net.WebUtility.HtmlCode()对注释进行解码

seCmd.Parameters["@Comments"].Value = System.Net.WebUtility.HtmlDecode(strComment);
您可以在客户端使用encodeURI()或encodeURIComponent(),在服务器端使用Url.Unescape()

而不是
数据:“{'args':'”+EditRecordArgs+“}”
作为我的想法更好地使用

data: "{'arg1': '" + arg1Value + "', arg2': '"+ arg2Value ...+" }"

为了避免
Trim

出现问题,我建议使用json对象,而不是传递逗号分隔的值。它将更加清晰,您可以轻松地传递值

创建一个JS类

EditRecordArgs = {};
EditRecordArgs.ServiceID = '“' + strServiceID+ '”'; 
EditRecordArgs.SupplierNo = '“' + strSupplierOrderNo + '”'; 
EditRecordArgs.Comment = '“' + strComment + '”'; 

用C语言上课#

在课堂上

使用名称空间

using System.Web.Script.Serialization;
在web方法中

ServiceRecord r = ser.Deserialize<ServiceRecord>(args); 
ServiceRecord r=ser.反序列化(args);

希望这对您有所帮助。

使用JSON字符串将数据发送到服务器,并从服务器反序列化数据

$("#btnEditFields").click(function () {
        //Store the New comment
       var data = {};
    data.strSupplierOrderNo =$("#<%=tbPopUpEditSuppOrdNo.ClientID%>").val();
    data.strComment =$("#<%=tbPopUpEditComments.ClientID%>").val();;
    .
    .
    .
    ...
        // Confirming the operation from the user
        if (confirm("You are about to add a new comment to order " + strPSTNNum + "?")) {
            $.ajax({
                type: "POST",
                //UpdateRecordInGridViewUsingAjax.aspx is the page name and UpdateOrder 
                // is the server side web method which actually does the updation
                url: "PSTN_OrderManagementTracker.aspx/updatePSTNDataInDB",
                //Passing the record id and data to be updated which is in the variable update_data
                data: {args: JSON.stringify(data)},
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                //Giving message to user on successful updation
                success: function () {
                    alert("Comment successfully added!!!");
                    location.reload(); 
                },
                error: function(xhr, ajaxOptions, thrownError){
                alert(thrownError);
            }
            });
        }
        return false;
    });
    });
$(“#btnEditFields”)。单击(函数(){
//存储新注释
变量数据={};
data.strSupplierOrderNo=$(“#”)val();
data.strComment=$(“#”)val();;
.
.
.
...
//确认来自用户的操作
如果(确认(“您将要向订单添加新注释”+strpstnum+“?”){
$.ajax({
类型:“POST”,
//UpdateRecordInGridViewUsingAjax.aspx是页面名称和UpdateOrder
//是实际执行更新的服务器端web方法
url:“PSTN_OrderManagementTracker.aspx/updatePSTNDataInDB”,
//传递变量update\ U data中要更新的记录id和数据
数据:{args:JSON.stringify(data)},
contentType:“应用程序/json;字符集=utf-8”,
数据类型:“json”,
//向用户发送更新成功的消息
成功:函数(){
警告(“添加评论成功!!!”;
location.reload();
},
错误:函数(xhr、ajaxOptions、thrownError){
警报(thrownError);
}
});
}
返回false;
});
});
以及背后的代码

[System.Web.Services.WebMethod]
public static void updatePSTNDataInDB(string args)
{
  var serializer = new JavaScriptSerializer();
  Dictionary<string, string> jsonObjects = serializer.Deserialize<Dictionary<string, string>>(args);

  strSupplierOrderNo =  jsonObjects[strSupplierOrderNo];
}
[System.Web.Services.WebMethod]
公共静态void updatePSTNDataInDB(字符串参数)
{
var serializer=新的JavaScriptSerializer();
Dictionary jsonObjects=序列化程序.反序列化(args);
strSupplierOrderNo=jsonObjects[strSupplierOrderNo];
}

根据描述,服务器端代码(目前问题中未显示)似乎存在SQL注入漏洞,这是一件非常糟糕的事情。您是如何写入数据库的?您可能不需要添加所有类型的编码,但是您确实需要正确地“转义”数据库的输入,以便它知道什么是文本和什么是控制字符。我已经添加了webmethod,也感谢David。您看到的错误是什么?它发生在哪里?代码似乎正在调用存储过程,因此问题可能出在存储过程代码中。您是否可以进行一些调试,并更具体地缩小问题发生时的范围,以及运行时的值是什么?webmethod不存在错误,因为在没有斜杠或撇号的情况下,一切正常,使用firebug,我得到了json的错误,但它没有达到web方法的程度。问题肯定是撇号和json,好像我
$("#btnEditFields").click(function () {
        //Store the New comment
       var data = {};
    data.strSupplierOrderNo =$("#<%=tbPopUpEditSuppOrdNo.ClientID%>").val();
    data.strComment =$("#<%=tbPopUpEditComments.ClientID%>").val();;
    .
    .
    .
    ...
        // Confirming the operation from the user
        if (confirm("You are about to add a new comment to order " + strPSTNNum + "?")) {
            $.ajax({
                type: "POST",
                //UpdateRecordInGridViewUsingAjax.aspx is the page name and UpdateOrder 
                // is the server side web method which actually does the updation
                url: "PSTN_OrderManagementTracker.aspx/updatePSTNDataInDB",
                //Passing the record id and data to be updated which is in the variable update_data
                data: {args: JSON.stringify(data)},
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                //Giving message to user on successful updation
                success: function () {
                    alert("Comment successfully added!!!");
                    location.reload(); 
                },
                error: function(xhr, ajaxOptions, thrownError){
                alert(thrownError);
            }
            });
        }
        return false;
    });
    });
[System.Web.Services.WebMethod]
public static void updatePSTNDataInDB(string args)
{
  var serializer = new JavaScriptSerializer();
  Dictionary<string, string> jsonObjects = serializer.Deserialize<Dictionary<string, string>>(args);

  strSupplierOrderNo =  jsonObjects[strSupplierOrderNo];
}