jquery跨域问题!

发布于 2024-11-07 20:21:52 字数 1007 浏览 3 评论 0原文

我创建了一个 post 类型的服务。当我从 jquery ajax 发送数据时,它不起作用。GET 类型的方法工作正常。 我也需要帖子类型。解决方案是什么。请帮忙。

var user = document.getElementById("uname").value;
         var pass = document.getElementById("pass").value;
         var utyp = document.getElementById("usertyp").value;
         //  alert("hi"+pass);

         var dat = { "uname": user, "pwd": pass, "utype": utyp };

         Data = JSON.stringify(dat);





     $.ajax({
             url: "http://192.168.1.9:450/Service.svc/Login_Insert",
             type: "POST",
             data:Data,
             contentType: "application/json; charset=utf-8",
             dataType: "jsonp",
             processdata: true,
             success: function res(msg) {
                 alert("hello" + msg);
             },
             error: function error(response) {

                 alert("error");
                 alert(response.responseText);
                 alert(JSON.stringify(response));
             }
         });

问候, 吉里布山

i have created a service of type post.When i am sending data from jquery ajax it is not working.Method of type GET working fine.
I need with post type also .what is the solution.Please help.

var user = document.getElementById("uname").value;
         var pass = document.getElementById("pass").value;
         var utyp = document.getElementById("usertyp").value;
         //  alert("hi"+pass);

         var dat = { "uname": user, "pwd": pass, "utype": utyp };

         Data = JSON.stringify(dat);





     $.ajax({
             url: "http://192.168.1.9:450/Service.svc/Login_Insert",
             type: "POST",
             data:Data,
             contentType: "application/json; charset=utf-8",
             dataType: "jsonp",
             processdata: true,
             success: function res(msg) {
                 alert("hello" + msg);
             },
             error: function error(response) {

                 alert("error");
                 alert(response.responseText);
                 alert(JSON.stringify(response));
             }
         });

Regards,
giri Bhushan

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

南渊 2024-11-14 20:21:52

使用JSONP解决跨域请求。这实际上是一种绕过浏览器安全模型的黑客攻击。它的工作原理是包含一个远程脚本块并在准备好时自动执行回调函数。这只能通过 GET 请求来完成

cross domain requests are solved using JSONP. This is effectively a hack to work around the browser security model. It works by including a remote script block and auto executing a callback function when ready. This can ONLY be done as a GET request

享受孤独 2024-11-14 20:21:52

一些提示:

  • 当您使用 jQuery 时,无需使用典型的 javascript 样式获取值。
  • JSON.stringyfy() 不是必需的,
  • 不要使用 DATA 作为变量名,误导(我认为 data 是 js 的保留关键字)

使用 JSONP 加载 JSON 块。会额外添加一个“?callback=?”添加到 URL 末尾以指定回调。

在这里我修改了您的代码

var user = $("#uname").val();
var pass = $("#pass").val();
var utyp = $("#usertyp").val();
var userData = { "uname": user, "pwd": pass, "utype": utyp };
$.ajax({
             url: "http://192.168.1.9:450/Service.svc/Login_Insert?callback=?",
             type: "POST",
             data:userData,          
             crossDomain:true
             contentType: "application/json; charset=utf-8",
             dataType: "jsonp",
             processdata: true,
             success: function res(msg) {
                 alert("hello" + msg);
             },
             error: function error(response) {
                 alert("error");
                 alert(response.responseText);
                 alert(JSON.stringify(response));
             }
         });

参考

some TIPS:

  • when u r using jQuery then no need to get value with typical javascript style.
  • JSON.stringyfy() is not necessary
  • dont use DATA as variable name, misleading ( i think data is reserved keyword for js)

Loads in a JSON block using JSONP. Will add an extra "?callback=?" to the end of your URL to specify the callback.

here i modified your code

var user = $("#uname").val();
var pass = $("#pass").val();
var utyp = $("#usertyp").val();
var userData = { "uname": user, "pwd": pass, "utype": utyp };
$.ajax({
             url: "http://192.168.1.9:450/Service.svc/Login_Insert?callback=?",
             type: "POST",
             data:userData,          
             crossDomain:true
             contentType: "application/json; charset=utf-8",
             dataType: "jsonp",
             processdata: true,
             success: function res(msg) {
                 alert("hello" + msg);
             },
             error: function error(response) {
                 alert("error");
                 alert(response.responseText);
                 alert(JSON.stringify(response));
             }
         });

REFERENCE

半城柳色半声笛 2024-11-14 20:21:52

在您调用的服务方法中,将这 4 行代码插入到下面函数的开头。

    public string GetEmployee(string id, string name, string email)
    {
        WebOperationContext.Current.OutgoingResponse.Headers.Add(
            "Access-Control-Allow-Origin", "*"); WebOperationContext.Current.OutgoingResponse.Headers.Add(
            "Access-Control-Allow-Methods", "GET"); WebOperationContext.Current.OutgoingResponse.Headers.Add(
            "Access-Control-Allow-Headers", "Content-Type, Accept");
        Employee employee = new Employee();
        employee.TRGEmpID = id;
        employee.First_Name = name;
        employee.Email = email;
        EmployeeManagement empMgmt = new EmployeeManagement();
        var json = new JavaScriptSerializer().Serialize(empMgmt.Search(employee).FirstOrDefault());
        return json;
    }

另外,在 svc 文件中,在函数之前添加这一行,如下所示。

        [OperationContract]
    [WebInvoke(Method = "GET",
       ResponseFormat = WebMessageFormat.Json,
       RequestFormat = WebMessageFormat.Json,
       BodyStyle = WebMessageBodyStyle.Bare)]
    string GetEmployees(string name);

如果你也需要 web.config,这里是

<?xml version="1.0"?>

<system.web>
    <compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
    <services>
        <service  name="EmployeeService.EmployeeSearchService" behaviorConfiguration="DefaultServiceBehavior">
            <endpoint binding="webHttpBinding" contract="EmployeeService.IEmployeeSearchService"      behaviorConfiguration="DefaultEPBehavior" />
        </service>
    </services>
    <behaviors>
        <endpointBehaviors>
            <behavior name="DefaultEPBehavior">
                <webHttp />
            </behavior>
        </endpointBehaviors>
        <serviceBehaviors>
            <behavior name="DefaultServiceBehavior">
                <serviceMetadata httpGetEnabled="true" />
                <serviceDebug includeExceptionDetailInFaults="true" />
            </behavior>
        </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
    To browse web app root directory during debugging, set the value below to true.
    Set to false before deployment to avoid disclosing web app folder information.
  -->
    <directoryBrowse enabled="true"/>
</system.webServer>

in your service method you are calling, insert these 4 lines of code in start of the function below.

    public string GetEmployee(string id, string name, string email)
    {
        WebOperationContext.Current.OutgoingResponse.Headers.Add(
            "Access-Control-Allow-Origin", "*"); WebOperationContext.Current.OutgoingResponse.Headers.Add(
            "Access-Control-Allow-Methods", "GET"); WebOperationContext.Current.OutgoingResponse.Headers.Add(
            "Access-Control-Allow-Headers", "Content-Type, Accept");
        Employee employee = new Employee();
        employee.TRGEmpID = id;
        employee.First_Name = name;
        employee.Email = email;
        EmployeeManagement empMgmt = new EmployeeManagement();
        var json = new JavaScriptSerializer().Serialize(empMgmt.Search(employee).FirstOrDefault());
        return json;
    }

also, in svc file add this line before your function like in the one below.

        [OperationContract]
    [WebInvoke(Method = "GET",
       ResponseFormat = WebMessageFormat.Json,
       RequestFormat = WebMessageFormat.Json,
       BodyStyle = WebMessageBodyStyle.Bare)]
    string GetEmployees(string name);

if you need web.config too, here it is

<?xml version="1.0"?>

<system.web>
    <compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
    <services>
        <service  name="EmployeeService.EmployeeSearchService" behaviorConfiguration="DefaultServiceBehavior">
            <endpoint binding="webHttpBinding" contract="EmployeeService.IEmployeeSearchService"      behaviorConfiguration="DefaultEPBehavior" />
        </service>
    </services>
    <behaviors>
        <endpointBehaviors>
            <behavior name="DefaultEPBehavior">
                <webHttp />
            </behavior>
        </endpointBehaviors>
        <serviceBehaviors>
            <behavior name="DefaultServiceBehavior">
                <serviceMetadata httpGetEnabled="true" />
                <serviceDebug includeExceptionDetailInFaults="true" />
            </behavior>
        </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
    To browse web app root directory during debugging, set the value below to true.
    Set to false before deployment to avoid disclosing web app folder information.
  -->
    <directoryBrowse enabled="true"/>
</system.webServer>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文