简体   繁体   English

从服务器端将字符串传递给JavaScript函数

[英]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. 我正在尝试将字符串参数从服务器端传递到javascript函数,该函数将发布到AJAX方法。 The html is dynamically generated at the server side and I'm calling the javascript function using onclick property. html是在服务器端动态生成的,我正在使用onclick属性调用javascript函数。 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: 这是我的javascript方法:

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: 这是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: 您传递给Web方法的JSON暗示它是一个数字值,请在param值周围添加引号:

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 如果始终将字符串传递给您的Request方法,则可以使用JSON.stringify正确处理

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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