简体   繁体   English

无法从javascript解析JSON

[英]can't parse JSON from javascript

I'm newbie in javascript and My project can't use AJAX or any Framework . 我是javascript新手,我的项目无法使用AJAX或任何Framework。 . .

It's simple code but still curious what's wrong with it 这是简单的代码,但仍然好奇它怎么了

    <html>
    <head>
    <script type="text/javascript" src="onejs.js"></script>
    <link href="onecss.css" rel="stylesheet" type="text/css" />
    </head>
    <body>
    <div id="myDiv" class="subMenu" onclick="test(this)">CLICK</div>
    </body>
    </html>

onejs.js onejs.js

function test(id) { 
    var s = document.createElement('script');
    s.id = 'dynScript';
    s.type='text/javascript';
    s.src = "http://echo.jsontest.com/one/111oneoneone/key/value";
    var obj = JSON.parse(s);
    id.innerHTML = (obj.key);
}

When I click in "CLICK" it doesn't change. 当我单击“单击”时,它不会更改。

You are trying to load JSON as if it was a JavaScript script. 您正在尝试像加载JavaScript脚本一样加载JSON。 It isn't, so you can't. 不是,所以您不能。

Normally you would use the XMLHttpRequest object for this type of job. 通常,您可以将XMLHttpRequest对象用于这种类型的作业。

However, since you are ruled out Ajax (the process of using JavaScript to make HTTP requests), this isn't an option, so you would have to embed the data into the HTML when it initially loads. 但是,由于排除了Ajax(使用JavaScript发出HTTP请求的过程),因此这不是一个选择,因此您必须在数据最初加载时将数据嵌入HTML中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM