GVKun编程网logo

jquery – 如何使用JSONP以及如何制作支持JSONP输出的REST Web服务?

6

在本文中,我们将带你了解jquery–如何使用JSONP以及如何制作支持JSONP输出的RESTWeb服务?在这篇文章中,同时我们还将给您一些技巧,以帮助您实现更有效的asp.net–如何使用jque

在本文中,我们将带你了解jquery – 如何使用JSONP以及如何制作支持JSONP输出的REST Web服务?在这篇文章中,同时我们还将给您一些技巧,以帮助您实现更有效的asp.net – 如何使用jquery“jsonp”调用外部Web服务?、jquery ajax中使用jsonp的限制解决方法_jquery、JQuery AJAX如何获取和解析JSONP而不是JSON?、jQuery Mobile App +远程REST Web服务:JSONP的替代品?

本文目录一览:

jquery – 如何使用JSONP以及如何制作支持JSONP输出的REST Web服务?

jquery – 如何使用JSONP以及如何制作支持JSONP输出的REST Web服务?

我有一个使用 Jquery Mobile制作移动Web应用程序的项目.我希望我的应用程序将使用来自跨域REST Web服务的数据.很多人说使用JSONP.但我仍然混淆如何使用它以及如何构建支持JSONP输出的REST Web服务.任何人都可以帮我讲述或说明JSONP的工作吗?或者任何人都有此案例的示例代码?谢谢你.

解决方法

JSONP是客户端请求,其中REST服务将是服务器端请求(仅当您尝试跨域api服务时).两者在过程方面都不同.

JSONP:

您可以使用javascript或使用jquery ajax方法实现JSONP.使用jquery实现是最简单的方法. JSONP是一种在html文档中动态包含javascript脚本的类型.所以你可以动态调用js函数.

JSONP工具有很多可用的资源.我参考下面的一个,

Check this for JSONP Implementation

下面是一个简单的jquery ajax函数,它触发jasonp请求到logitude和latitude.

$.ajax({
        type: "GET",dataType: "jsonp",cache: false,url: 'http://api.ipinfodb.com/v3/ip-city/?key=b518527dd751af36c974e0adcdc4cb329917df46c006a72bf92858dd7c059488&ip=<?=$client_ip?>&format=json',success: function(data) {           
            alert(data.latitude+":"+data.longitude)                             
        },error: function(){
            alert('Could not able to find location!');
        }
    });

检查this article for REST Implemenation

我希望这能帮到您.

asp.net – 如何使用jquery“jsonp”调用外部Web服务?

asp.net – 如何使用jquery“jsonp”调用外部Web服务?

我之前有一个问题 can jquery ajax call external webservice?

一些优秀的开发人员回答我使用jsonp,但我不知道如何使用它,我试图使用此代码调用我的服务:

$.ajax({
            type: "POST",url: "http://localhost:1096/MySite/WebService.asmx?callback=?",data: "{}",contentType: "application/json; charset=utf-8",dataType: "jsonp",success: function(msg) {alert(msg);}
            });

这是我的服务代码:

[WebMethod]
public string HelloWorld() {
    return "Hello World " ;
}

任何人都有例子或可以为我解释这个问题?

更新:
我再次编写代码是这样的:

$.getJSON("http://localhost:1096/YourShoppingTest1/WebService.asmx/HelloWorld?jsonp=?",{name:"test"},function(data){
    alert(data.x);
    });

和这样的服务:

[WebMethod]
public string HelloWorld(string name)
{
    return "( {\"x\":10,\"y\":100} )";
}

但它总是在回来时给我这个错误:“丢失;在声明之前
[打破此错误]({“x”:10,“y”:100})“

并且从不调用成功函数,任何人都可以帮忙吗?

解决方法

我有一个类似的问题,不幸的是我没有手头的代码.

从记忆里:

>将[ScriptService]作为属性添加到Web方法中
>还要更改您的网址以调用HelloWorld过程.
像http://localhost:1096/MySite/WebService.asmx/HelloWorld?callback这样的东西

见:What are some good examples of JQuery using JSONP talking to .net?& What is the best way to call a .net webservice using jquery?

jquery ajax中使用jsonp的限制解决方法_jquery

jquery ajax中使用jsonp的限制解决方法_jquery

jsonp 解决的是跨域 ajax 调用的问题。为什么要跨域 ajax 调用呢?这样可以在一个应用中直接在前端通过 js 调用另外一个应用(在不同的域名下)的 API。
我们在实际应用中也用到了 jsonp ,但之前只知道 jsonp 的一个限制,只能发 get 请求,get 请求的弊端是请求长度有限制。
今天,发现 jsonp 的另外一个限制(在jquery ajax的场景下) —— 不会触发 $.ajax 的error callback,示例代码如下:

复制代码 代码如下:

$.ajax({
    dataType: ''jsonp'',           
    error: function (xhr) {
        //出错时不会执行这个回调函数
    }
});

这个限制由 jsonp 的实现机制决定。

解决方法:

使用一个 jquery 插件 —— jquery-jsonp,https://github.com/jaubourg/jquery-jsonp

示例代码:

复制代码 代码如下:


复制代码 代码如下:

$.jsonp({
    url: '''',
    success: function (data) {
    },
    error: function (xOptions, textStatus) {
        console.log(textStatus);
    }
});

当 jsonp 请求出错时,比如 404 错误,error 回调函数会执行,输出字符串"error"。

JQuery AJAX如何获取和解析JSONP而不是JSON?

JQuery AJAX如何获取和解析JSONP而不是JSON?

摘要
我有一个运行搜索的应用程序.在允许提交之前,它会向查询发送 AJAX调用以检查有效的邮政编码,然后返回我可以解析的 JSON结果.我现在需要跨域做同样的事情,我知道我必须使用完整的URL和JSONP格式,但我不知道如何设置它.

AJAX电话

我发送了一个通过查询运行的邮政编码.

if (zipLength == 5) {
    $.ajax({
        type:"GET",//location of the cfc
        url: "cfc/test.cfc",//function name and url variables to send
        data: {method:'zip_lookup',zip:zip},//function run on success takes the returned json object and reads values.
        success: function(obj) {
            var response = $.parseJSON(obj);

            if (response.formError == true) {
                alert(response.message);
            }
        }
    });
}

运行查询的Coldfusion中的CFC

<!---Makes sure entered zip exists--->   
<cffunction name="zip_lookup" access="remote">
    <cfquery name="qZip">
        Select distinct ZipCode
        From zipcodes
        Where ZipCode = '#url.zip#'
    </cfquery>

    <!---Return an error if zip was not found--->
    <cfif qZip.RecordCount EQ 0>
        <cfset formError = true>
        <cfset message = "Invalid Zip">
    <cfelse>
        <cfset formError = false>
        <cfset message = "">   
    </cfif>

    <cfoutput>
        <cfset obj = 
            {
                "formError" = formError,"message" = message
            } 
        />
    </cfoutput>

    <cfprocessingdirective suppresswhitespace="Yes"> 
        <cfoutput>
            #serializeJSON(obj)#
        </cfoutput>
    </cfprocessingdirective>

    <cfsetting enablecfoutputonly="No" showdebugoutput="No">
</cffunction>

JSON响应

这是查询返回的内容.

{"message":"Invalid Zip","formError":true}

处理响应

正如我在AJAX成功函数中所做的那样,我可以从JSON响应中获取formError或消息变量.我怎么能用JSONP做到这一点?

success: function(obj) {
    var response = $.parseJSON(obj);

    if (response.formError == true) {
        alert(response.message);
    }
}

解决方法

我有答案.

请注意,原始发布的代码与正常的JSON响应完美配合.

这是我获得JSONP响应的方式.

AJAX电话

$.ajax({
    type:"GET",//Location of the cfc
    url: "http://yourFullUrl/test.cfc",//Function name and url variables to send
    data: {method:'zip_lookup',//Set to JSONP here
    dataType:"jsonp",//The name of the function that's sent back
    //Optional because JQuery will create random name if you leave this out
    jsonpCallback:"callback",//This defaults to true if you are truly working cross-domain
    //But you can change this for force JSONP if testing on same server
    crossDomain:true,//Function run on success takes the returned jsonp object and reads values.
    success: function(responseData) {
        //Pulls the variables out of the response
        alert(responseData.formError);
        alert(responseData.message);
    }
});

运行查询的Coldfusion中的CFC

<cffunction name="zip_lookup" access="remote" returntype="string" returnformat="plain" output="false">

    <cfquery name="qZip">
        Select distinct ZipCode
        From zipcodes
        Where ZipCode = '#url.zip#'
    </cfquery>

    <!---Return an error if zip was not found--->
    <cfif qZip.RecordCount EQ 0>
        <cfset formError = true>
        <cfset message = "Invalid Zip">
    <cfelse>
        <cfset formError = false>
        <cfset message = "">   
    </cfif>


    <cfoutput>
        <cfscript>
           <!---Important to have double quotes around the name and value. --->
           <!---I missed this before --->
           return '#arguments.callback#({"formError": "#formError#","message": "#message#"});';
       </cfscript>
    </cfoutput>

</cffunction>

格式化的JSONP响应

//Using the name from the jsonpCallback setting in the AJAX call
callback({"formError": "true","message": "Invalid Zip"});

jQuery Mobile App +远程REST Web服务:JSONP的替代品?

jQuery Mobile App +远程REST Web服务:JSONP的替代品?

如何解决jQuery Mobile App +远程REST Web服务:JSONP的替代品??

| 目前,我正在jQuery Mobile网站上工作,该网站随后将通过Titanium转换为应用程序。我创建了一个RESTful JSON Web服务,该服务在与jQuery Mobile应用程序不同的服务器上运行。使用JSONP通过AJAX使用Web服务。 我感到烦恼的一件事是,我无法使用HTTP错误代码,因为只要服务器发出错误,jQuery就会自动中止JSONP调用。我永远无法掌握客户端的错误代码。 另一件事是JSONP仅与HTTP动词GET一起使用,例如,您不能发出JSONP POST(当前,Web服务仅是GET,但可能会更改)。 JSONP是否有其他选择?还是将JSONP Web服务与AJAX结合使用时,JSONP是我唯一的选择吗?例如,Twitter应用程序如何与Twitter API(它们具有REST API)交互?     

解决方法

        您的问题很好地说明了为什么人们抱怨jquery太容易采用;) JSONP不是ajax。没有成功和失败回调。 JSONP是这样的: 将参数放在网址中 添加&jsoncallback = random2745273 创建一个全局变量
random2745273
,并将回调引用放入其中 将
<script src=\"theurlhere\"></script>
加到
head
那就是您所能做的。 服务器返回
random2745273({somedata});
这就是调用回调的方式。 如果要报告错误,则服务器必须生成正确的代码。您将不知道发送了哪些HTTP标头。 这是您与api进行跨域通信的唯一方法。 通过生成iframe也可以发送跨域通信,但是它很笨拙,很少使用。 [编辑] 好的,这让我开始思考...我可以使用iframe hack来封装JSONP! 和往常一样-我不是第一个想到这个主意的人(我终于谦虚地用谷歌搜索我的想法了;)) 它在这里:http://beebole.com/en/blog/general/sandbox-your-cross-domain-jsonp-to-improve-mashup-security/ 很棒 [edit2] 噢,我忘了...还有另一个。
window.postMessage
它已经在某些浏览器中实现。如果您不必与大多数浏览器兼容,则可以立即开始使用它! :)     ,        在对postMessage进行更多研究之后,我找到了JSONP的替代方法:通过EasyXDM通过跨域消息传递进行AJAX。 参见http://easyxdm.net/wp/2010/03/17/cross-domain-ajax/     

我们今天的关于jquery – 如何使用JSONP以及如何制作支持JSONP输出的REST Web服务?的分享就到这里,谢谢您的阅读,如果想了解更多关于asp.net – 如何使用jquery“jsonp”调用外部Web服务?、jquery ajax中使用jsonp的限制解决方法_jquery、JQuery AJAX如何获取和解析JSONP而不是JSON?、jQuery Mobile App +远程REST Web服务:JSONP的替代品?的相关信息,可以在本站进行搜索。

本文标签:

上一篇使用jQuery将多个参数传递给ASP.NET Web API

下一篇jquery – 以全屏模式启动移动webapp(js移动端全屏)