gpt4 book ai didi

javascript - 如何根据 URL 的输出设置 JavaScript 数组?

转载 作者:行者123 更新时间:2023-11-28 21:03:03 26 4
gpt4 key购买 nike

我有一个 MVC 应用程序,当我访问某个 URL 时,它会在浏览器中生成以下输出:

[{"name":"Victoria Day","date":"\/Date(1337583600000)\/"},{"name":"Canada Day","date":"\/Date(1341212400000)\/"},{"name":"Civic Holiday","date":"\/Date(1344236400000)\/"},{"name":"Labour Day","date":"\/Date(1346655600000)\/"},{"name":"Thanksgiving","date":"\/Date(1349679600000)\/"},{"name":"Remembrence Day","date":"\/Date(1352707200000)\/"},{"name":"Christmas","date":"\/Date(1356422400000)\/"},{"name":"Boxing Day","date":"\/Date(1356508800000)\/"}]

当然,源代码周围有一堆 html 标签。

如何将此原始信息分配给 Javascript 数组?

最佳答案

考虑到您的 http 请求返回您发布的原始数据,您应该能够使用:

var text = $.trim($(document.body).text());
var cleanedText = text.replace(/\\\/Date\(/g,"").replace(/\)\\\//g,"");
var holidays = $.parseJSON(cleanedText); // This is your array!

alert("Loaded " + holidays.length + " holidays. Fifth one is " + holidays[4].name + " celebrated on " + new Date(parseInt(holidays[4].date)).toString());

// Output(the dates should be printed with your preferred timezone offset):
// Loaded 8 holidays. Fifth one is Thanksgiving celebrated on Mon Oct 08 2012 10:00:00
// GMT+0300 (GTB Daylight Time)

如果您想要解析的输出位于其他位置,您应该使用自定义选择器通过 jQuery 在 var text 中加载它。请注意,var cleanedText 从日期值中删除错误字符,以便将它们解析为有效的 javascript Date 对象。

如果您还有其他问题,请发表评论。祝你好运!

​JSFiddle 工作示例:click here

编辑:您需要 jQuery .

Edit2: 我认为您需要使用 $.get 才能从自定义网址检索数据(确保它来自同一服务器,否则您可能会运行浏览器安全问题)。您应该尝试一下,并尝试检查您的请求是否到达服务器上的正确路径(例如,您可以在“网络”选项卡上的“开发人员工具”下的 Google Chome 浏览器上检查所有请求数据)。您应该更改 function(data) { 的内容以满足您的需求。

var url = 'page.html'; // You should change this with the url that returns your data.
$.get(url, function(data) {
alert('The response is: ' + data); // Make sure it's ok
var text = $.trim(data);
var cleanedText = text.replace(/\\\/Date\(/g,"").replace(/\)\\\//g,"");
var holidays = $.parseJSON(cleanedText); // This is your array!

alert("Loaded " + holidays.length + " holidays. Fifth one is " + holidays[4].name + " celebrated on " + new Date(parseInt(holidays[4].date)).toString());
});

关于javascript - 如何根据 URL 的输出设置 JavaScript 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10523557/

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