gpt4 book ai didi

javascript - 如何在面向对象的 Javascript 中使用 JSONP

转载 作者:行者123 更新时间:2023-11-29 15:39:32 25 4
gpt4 key购买 nike

我是 JSONP 的新手,已经为我的应用程序实现了跨域功能,并且一切正常。现在我想更改我的 javascript 代码以应用面向对象。

我的接口(interface)是

http://localhost:8080/myApplication/getComments?callback=displayComments

CrossDomain.prototype.displayComments = function(data) {
// code to display the comments
}

现在我在下面给出的 Firebug 中遇到错误

ReferenceError: displayComments is not defined

我把api改成了

http://localhost:8080/myApplication/getComments?callback=this.displayComments

并且发现函数是这样内联附加到回调中的

http://localhost:8080/myApplication/getComments?callback=callback=function (jsonData)
{
//code to display the comments
}

这次是 Firebug 的另一个错误

SyntaxError: function statement requires a name

我怀疑是否在面向对象的 javascript 中使用 JSONP。请帮忙。

提前致谢。

最佳答案

除非您要创建该函数的实例,否则在函数原型(prototype)上定义函数是没有意义的,所以从这样做开始吧。

var myCrossDomain = new CrossDomain();

然后你必须在对象上调用方法,而不是作为一个全局的(它不是一个全局的,所以你无论如何不能这样做)

var uri = "http://localhost:8080/myApplication/getComments?callback=" + 
encodeURIComponent("myCrossDomain.displayComments");

回应编辑和评论:

Yes i am creating an instance of this in another js file

然后如上所示引用它。

I changed the api to

http://localhost:8080/myApplication/getComments?callback=this.displayComments

这是 JSON-P。它通过添加一个新的脚本元素来运行。一切都在全局范围内被调用。这将调用 this.displayComments,它与 window.displayComments 相同。

如果你想直接调用你的方法,那么你需要明确指定持有实例的全局变量。

如果你不想直接调用它,那么你可以使用更传统的方法生成一个新的匿名函数,该函数可以通过闭包访问所述对象,将该函数分配给全局变量(具有唯一名称) 并使用该名称作为回调参数。

and found that the function is appended inline to the callback like this

http://localhost:8080/myApplication/getComments?callback=callback=function (jsonData)

您还没有向我们展示创建 URI 的代码,因此我们不知道为什么会这样。

关于javascript - 如何在面向对象的 Javascript 中使用 JSONP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21670909/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com