简体   繁体   中英

Passing string to JavaScript function from the server side

I'm trying to pass a string parameter to a javascript function from the server side which will be posted to an AJAX method. The html is dynamically generated at the server side and I'm calling the javascript function using onclick property. The problem is that it works for a numeric value but I get an internal server error when I pass in a string value.

here's my server side code:

str.Append("<span class=\"button-accept\"><a class=\"btn btn-primary btn-sm\" onclick=\"Request('"+from.ToString()+"')\" href=\"#\"><i class=\"fa fa-check\"></i></a></span>");

Here's my javascript method:

function Request(param) {
        $.ajax({
            type: "POST",
            url: '<%= ResolveUrl("~/myaccount/notifications/Default.aspx/Accept") %>',
            data: "{'param' : "+param+"}",
            contentType: "application/json",
            success: function (msg) {
                msg = msg.hasOwnProperty("d") ? msg.d : msg;
                alert(msg);
            }
        });
    }
    function OnSuccess(response) {
        alert(response.d);
    }

and here's the method that will be called by AJAX:

        [WebMethod]
    public static string Accept(string param)
    {
        return param;
    }

What's the right way to do this?

The JSON you are passing to the web method is implying that it is an numeric value, add quotes surrounding the param value:

Old

data: "{'param' : "+param+"}",

New

data: "{'param' : '"+param+"'}",

Alternatively ...

If a string is always passed to your Request method, it will be correctly handled using JSON.stringify

data: JSON.stringify({ 'param' : param }),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM