web service call from javascript

不想你离开。 提交于 2019-12-25 01:33:24

问题


I am calling a webservice in javascript file using json but web service is called only when both of the .asmx file and javascript file are on my local server or both of the files are uploaded on live server.

but I want to test my webservice which is uploaded on my live server from my local server.

So please tell me the way by which I can test my live webservice from my local server. Because same web service is working fine when my Javascript file also present on live but not working when javascript file is on local and web service is on live server

Please HELP


回答1:


The problem is that you are trying to make request to another domain.

You can try to use crossDomain option of jQuery.ajax call.

https://api.jquery.com/jQuery.ajax/




回答2:


you can call the web service which is on same domain beacuse of some Security reasons.u will have to use JSON with padding (JSONP).

Your service has to return jsonp, which is basically javascript code. You need to supply a callback function to the service from your ajax request, and what is returned is the function call.

Example: 1

Ajax Request:

    function hello() {

        $.ajax({
            crossDomain: true,
            contentType: "application/json; charset=utf-8",
            url: "http://example.example.com/WebService.asmx/HelloWorld",
            data: {}, // example of parameter being passed
            dataType: "jsonp",
            success: jsonpCallback,

        });
    }

    function jsonpCallback(json) {
        document.getElementById("result").textContent = JSON.stringify(json);
    }

Server-side Code:

public void HelloWorld(int projectID,string callback)
{

    String s = "Hello World !!";
    StringBuilder sb = new StringBuilder();
    JavaScriptSerializer js = new JavaScriptSerializer();
    sb.Append(callback + "(");
    sb.Append(js.Serialize(s));
    sb.Append(");");
    Context.Response.Clear();
    Context.Response.ContentType = "application/json";
    Context.Response.Write(sb.ToString());
    Context.Response.End();
}

Example:2 How can I produce JSONP from an ASP.NET web service for cross-domain calls?



来源:https://stackoverflow.com/questions/23520590/web-service-call-from-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!