从客户端网站使用 ajax/jquery 将参数传递给 Web 服务方法

From client website pass parameters to webservice method using ajax/jquery

本文关键字:参数传递 Web 方法 服务 jquery 网站 客户端 ajax      更新时间:2023-09-26

我有两个网站

  1. 同步测试网站
  2. 远程网站(客户网站)

SysteTest网站包含一个Web服务"Service.svc",方法如下

[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]<br>
public class Service
{
    [OperationContract]
    public void DoWork()
    {
        // Add your operation implementation here
        return;
    }
    [OperationContract]
    [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)]
    public string SyncJson(string p1)
    {
        return p1;
    }
    // Add more operations here and mark them with [OperationContract]
}

我想从RemoteWebsite的HTML页面访问此方法,以下是此HTML页面的代码。

    function SyncJson() {
        var sPhone = "test data";
        var data = { p1: sPhone };
        data = JSON.stringify(data);
        $.ajax({
            type: "POST",
            contentType: "application/json;",
            url: "http://mydomain:12887/Service.svc/SyncJson",
            data: data,
            dataType: 'json',
            success: function () {
                alert('success');
            },
            error: function (msg) {
                console.log(msg);
                alert(msg.d);
            }
        });
    }

<p>
    Remote site
    <input type="button" onclick="SyncJson()" value="Send Test Data" />
</p>

但是我得到了这个错误:

网络错误: 405 方法不允许 - http://abc.com/Service.svc/SyncJson

这是跨域请求。创建服务时应考虑这一点。阅读更多关于 CORS 的信息。