通过ajax将参数传递给webservice

本文关键字:webservice 参数传递 ajax 通过 | 更新日期: 2023-09-27 18:02:44

我有一个简单的web服务,只有一个参数:

public static string LoadComboNews(string id)
{
    string strJSON = "";
    DataRowCollection people = Util.SelectData("Select * from News where person = "+ id +" Order by NewsId desc ");
    if (people != null && people.Count > 0)
    {
        //temp = new MyTable[people.Count];
        string[][] jagArray = new string[people.Count][];
        for (int i = 0; i < people.Count; i++)
        {
            jagArray[i] = new string[] { people[i]["NewsID"].ToString(), people[i]["Title"].ToString() };
        }
        JavaScriptSerializer js = new JavaScriptSerializer();
        strJSON = js.Serialize(jagArray);
    }
    return strJSON;
}

在javascript上,我试图用参数来调用它:

jQuery.ajax({
        type: "POST",
        url: "webcenter.aspx/LoadComboNews",
        data: "{'id':usrid}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            // Replace the div's content with the page method's return.
            combonews = eval(msg.d);
        }
    });

更新:

usrid是动态的

我在这里做错了什么吗?

通过ajax将参数传递给webservice

您发送的数据无效"{'id':usrid}"

这不是一个有效的json你可能会假设usrid是一个变量

"{'"id'":"+usrid+"}"

你不应该执行这个命令吗

Select * from News where person = '"+ id +"' Order by NewsId desc

考虑id是字符串

也试试这个

combonews = JSON.stringify(msg);

为方法添加WebMethod

[WebMethod]
public static string LoadComboNews(string id)

试试这个格式

$.ajax({
    type: "POST",
    url: "webcenter.aspx/LoadComboNews",
    data: '{"id":"usrid"}',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (msg) {
        // Replace the div's content with the page method's return.
        alert(msg.d);
    },
    error: function (jqXHR, textStatus, errorThrown) {
        console.log(textStatus, errorThrown);
        alert(textStatus + " " + errorThrown);
    }
});

data: '{"id":"' + usrid + '"}',