【问题标题】:how to call web service from javascript (ajax)如何从 javascript (ajax) 调用 Web 服务
【发布时间】:2015-08-06 04:54:57
【问题描述】:

我有 1 个项目 webservice 和 1 个项目 web asp.net 我想通过 json(ajax) 插入数据 我通过后面的代码测试了文件服务,它很好, 代码js有错误 文件 WebService1:

public bool HelloWorld(student obj) {
    SqlConnection cnn = new SqlConnection("Data Source=PHAMHOP-LAPTOP\\SQLEXPRESS;Initial Catalog=qlsv;Integrated Security=True");
    cnn.Open();
    SqlCommand cmd = new SqlCommand("insert into sinhvien(name,age) values(@name,@age)", cnn);
    cmd.Parameters.AddWithValue("name", obj.name);
    cmd.Parameters.AddWithValue("age", obj.age);
    int row = cmd.ExecuteNonQuery();
    if (row == 1){
        return true;
    } else {
        return false;
    }
}

文件aspx:

<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
    function add() {
        $.ajax({
            type: "POST",
            url: "http://localhost:51097/Service1.asmx/HelloWorld",
            data: "{'id':'1' ,'name': 'Amit', 'age': '97'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                alert("ok");
            }
        });
    }
</script>
<body>
    <input type='Button' value='gui' OnClick='add()'/>
</body>

它不起作用。

【问题讨论】:

  • 尝试删除contentType: "application/json; charset=utf-8", dataType: "json",
  • It does not work 无济于事。发布您从浏览器控制台收到的实际错误消息。
  • 它调用函数成功,但没有调用服务,兄弟@Singh

标签: javascript c# jquery asp.net ajax


【解决方案1】:

由于返回的数据不是JSON,所以不需要contentType: "application/json; charset=utf-8", dataType: "json",data选项也不需要是字符串。将其作为对象传递。

试试这个

function add() {
    $.ajax({
        type: "POST",
        url: "http://localhost:51097/Service1.asmx/HelloWorld",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: {
            id: 1,
            name: 'Amit',
            age: 97
        },
        success: function (msg) {
            alert("ok");
        }
    });
}

【讨论】:

  • “contentType”与返回的数据有什么关系?不就是指定发送给服务器的数据,而不是从服务器返回的数据吗?
【解决方案2】:

或者,您可以尝试将 JSON 作为字符串参数而不是作为学生传递,然后使用 Newtonsoft 或 System.Web.Script.Serialization.JavaScriptSerializer 自行反序列化。

bool HelloWorld(string obj)

而不是

bool HelloWorld(student obj)

【讨论】:

  • try passing the JSON as a string - JSON 一个字符串
猜你喜欢
  • 2017-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-26
  • 1970-01-01
  • 2014-02-12
  • 2015-11-15
  • 1970-01-01
相关资源
最近更新 更多