【问题标题】:Return JSON created in JavaScript HTML Page返回在 JavaScript HTML 页面中创建的 JSON
【发布时间】:2014-07-23 10:00:56
【问题描述】:

我有两个 HTML 页面:

1) 第一个 HTML 页面 (page1.html):

<html lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function () {
        event.preventDefault();

        function json1(id,name){
            this.id = id;
            this.name = name;
        }

        id_list = Array();
        id_list.push(new json1("1","TEST_1");
        id_list.push(new json1("2","TEST_2");
        id_list.push(new json1("3","TEST_3");
        id_list.push(new json1("4","TEST_4");
        id_list.push(new json1("5","TEST_5");

        id_list = JSON.stringify(id_list);
        document.write(id_list);
    });
 </script>
 </head>
 </html>

2) 第二个 HTML 页面 (page2.html):

<html lang="en">
<head>
<meta http-equiv="Content-Type" content="application/json; charset=utf-8" > 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function () {
        event.preventDefault();

        $.ajax({
            url : 'http://www.mydomain.com/page1.html',
            type : 'POST',
            async: false,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data){
                alert("Return OK");
            },
            error: function(xhr, ajaxOptions, thrownError){
                alert('ERROR = ' + xhr.status + ' - ' + thrownError);
            }       
        });
     });
 </script>
 </head>
 </html>

当我执行http://page2.html 时,.ajax 返回我: ERROR = 200 SyntaxError - Unexpected token

当我将 dataType: "json" 更改为 "text" 时,.ajax 将返回 page1 的所有代码 HTML。

我需要返回在 page1.html 中创建的 JSON。

谁能帮帮我?

谢谢

ps:对不起我的英语。

【问题讨论】:

  • Ajax 并没有真正在外部页面上执行 javascript,它只是返回该页面的内容,这就是为什么你得到 整个页面,这就是它的工作方式,你做错了。
  • 您似乎误解了如何创建 JSON 响应。您正在向 HTML 页面发出请求,因此您正在检索所有 HTML 源代码,包括未解释的 JS。如果要返回 JSON,则需要将 JSON 字符串作为唯一返回的文本。由于您所看到的原因,使用客户端 JavaScript 是不可能的。您应该将您的 JSON 提要修改为服务器端资源。

标签: javascript jquery html ajax json


【解决方案1】:

首先你在第一个html页面上有错误

    id_list = Array();
    id_list.push(new json1("1","TEST_1"));
    id_list.push(new json1("2","TEST_2"));
    id_list.push(new json1("3","TEST_3"));
    id_list.push(new json1("4","TEST_4"));
    id_list.push(new json1("5","TEST_5"));

您忘记在每个push 调用的末尾添加)

第二件事是,当您使用 ajax 时,您是在询问服务器,而在这种情况下服务器返回

<html lang="en">
<head>
<script ...

ajax 函数将此作为结果,不执行任何 javascript 代码,也不等到就绪事件

要返回的第一个html页面的结果是

[{"id":"1","name":"TEST_1"},{"id":"2","name":"TEST_2"},{"id":"3","name":"TEST_3"},{"id":"4","name":"TEST_4"},{"id":"5","name":"TEST_5"}]

如果你只是把这个 json 字符串放在你的第一个 html 页面中,没有任何 html 标记,一切都会正常工作

我建议您使用 php 或 nodejs 之类的服务器端代码以 json 而非纯 javascript 返回您需要的结果,因为它是客户端语言

【讨论】:

    【解决方案2】:

    这里你已经将数据类型指定为“Json”,所以响应必须是完整的 JSON 对象,否则 会出现同样的问题。

    在您的代码中,响应不符合 JSON 格式。

    示例 JSON

    {"employees":[
    {"firstName":"John", "lastName":"Doe"}, 
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
    ]}
    

    只需复制上面的代码并粘贴到 Page1.html 中并立即尝试。 [注意:Page1.html页面只包含以上代码]

    【讨论】:

      【解决方案3】:

      您是否有能力使用服务器端语言,例如 PHP?您可以使用 PHP 在 page1 上构建您的 JSON 输出。 page1 上的唯一输出应该是 JSON,这是从 page2 上的 AJAX 请求中检索信息的正确方法。

      当你通过 AJAX 调用另一个页面时,它不会执行 JS,这需要在服务器端完成。

      【讨论】:

        【解决方案4】:

        正如@Rory McCrossan 所说,如果您发出 POST 请求,您只会获得第一页的源代码。但是,如果您希望第一个页面生成自定义 JSON 并发送回父页面,那么您可能可以创建一个隐藏的 iFrame。 iFrame 将重定向到第一页,第一页将使用跨文档消息发送回父页面的消息。

        你可以试试下面的 HTML 代码。我还没有测试它,所以它可能会给出一些错误。

        第一个 HTML 页面

        <!DOCTYPE HTML> 
        <html> 
        
        <head> 
            <title> "First Page" </title>     
            <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> 
        </head> 
        
        <body> 
            
        <script> 
        
            // You can add your logic to geerate JSON
            var customJSON = "[{"id":"1","name":"TEST_1"},{"id":"2","name":"TEST_2"},{"id":"3","name":"TEST_3"},{"id":"4","name":"TEST_4"},{"id":"5","name":"TEST_5"}]" 
        
            // Send a message for the outer page
            window.top.postMessage(customJSON, '*')
        
        </script> 
        </body> 
        
        </html> 
        

        第二个 HTML 页面

        <HTML >
            
        <head> 
            <title> "Second page"</title>     
            <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> 
        </head> 
        
        <body style="text-align:center;">
        
        <h1>Second page</h1>
        <p id="Message"></p>
              
        <iframe src="http://example.com/page1.html" height="500" width="300" title="Iframe Example"  id="iframe" style="display:none;" ></iframe>
        
        <script> 
        
            // Receive message from the iFrame
        
            window.onmessage = function(e){    
            document.getElementById("Message").innerHTML = e.data
            console.log("e.data", e.data)
        };
            
        </script> 
        
        </body> 
        </HTML>
        

        参考:-

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-08-27
          • 1970-01-01
          • 2018-12-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-08-11
          相关资源
          最近更新 更多