Remote json and Javascript

Remote json and Javascript

本文关键字:Javascript and json Remote      更新时间:2023-09-26

我目前正在为我工作的学校开发一个Web应用程序。我们的一台专用服务器上有一个名为FROG的程序。不幸的是,这被锁定得非常严格,您可以使用 gui 创建网站。你能做的最多的编码是HTML和javascript。

我希望能够从我们也拥有的远程服务器检索信息。由于跨域限制,我无法使用 ajax。但是我想出了一个解决方法。

我在远程服务器上一个名为 xrequest 的文件中有此函数调用.js:

loadNotices({[{title: 'this is a test'},{title: 'this is another test'}]});

这只是一个函数调用,其中 json 对象作为参数传递(参数最终将从数据库中检索的数据生成)。

在我的其他受限服务器上,我有这个javacript:

<script type="text/javascript">
function loadNotices(data)
{
    alert(data);
}
var url = "http://somedomain.com/tests/xrequest.js";
var script = document.createElement('script');
script.setAttribute('src', url);
document.getElementsByTagName('head')[0].appendChild(script); 
</script>
<div id="notices"></div>

我想做的是遍历 xrequest.js 文件中的每个标题,并将它们显示为列表。

我不确定如何循环浏览标题。

如果您需要更多信息,请发表评论。任何帮助都是值得赞赏的。

非常感谢

菲尔

要遍历标题,首先需要删除数组周围的大括号。之后,循环浏览如下所示的标题:

function loadNotices(arr) {
    var title, i = 0;
    for (; i < arr.length; i++) {
        title = arr[i].title;
    }
}​

另外,考虑更改:

document.getElementsByTagName('head')[0].appendChild(script); 

document.head.appendChild(script); 

您的实现看起来像 JSONP 调用。使用Jquery,您可以使其变得简单

$.get('url?callback', {<data>}, function(data){
});

在 URL 末尾?callback,jQuery 自动创建一个随机回调函数。在您的服务器上,您可以在其周围添加包装器回调函数,而不是返回正常的 JSON。PHP 示例:

$callback = $_GET['callback'];
echo $callback.'('.json_encode(obj).');';

这将成为

callback({your return data>});

您的脚本将收到该消息。

loadNotices({[{title: 'this is a test'},{title: 'this is another test'}]});

此函数调用不正确,请改为执行以下操作:

loadNotices([{title: 'this is a test'},{title: 'this is another test'}]);

然后你可以像这样循环浏览你的标题

for (i = 0; i < titles.length; i++){
   alert(titles[i].title);
}