将参数传递给ajax上的Web服务

时间:2013-03-07 19:03:55

标签: c# javascript jquery ajax

我有一个带有一个参数的简单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是动态的

我在这里做错了吗?

2 个答案:

答案 0 :(得分:1)

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

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

"{\"id\":"+usrid+"}"

用它来执行此命令

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

考虑id是一个字符串

也试试这个

combonews = JSON.stringify(msg);

答案 1 :(得分:1)

将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 + '"}',
相关问题