1

I've two HTML pages:

1) First HTML Page (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) Second HTML Page (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>

When I execute http://page2.html, .ajax returns me: ERROR = 200 SyntaxError - Unexpected token <

When I change the dataType: "json" to "text", the .ajax returns me all code HTML of page1.

I need to return the JSON created in page1.html.

Anybody can help me ?

Thanks

ps: sorry about my English.

Ronaldo Araujo
  • 13
  • 1
  • 1
  • 4
  • Ajax doesn't really execute the javascript on the external page, it just returns the content of that page, which is why you're getting the **whole page**, that's the way it works, and you're doing it wrong. – adeneo Jul 23 '14 at 10:02
  • 5
    You seem to be misunderstanding how to create a JSON response. You are making a request to the HTML page, so you are retrieving all the HTML source code, including the uninterpreted JS. If you want to return JSON, you need to have the JSON string as the only text returned. This is not possible using client side JavaScript for the reason you've seen. You should amend your JSON feed to be a server-side resource. – Rory McCrossan Jul 23 '14 at 10:03

4 Answers4

0

Here you have specified datatype as "Json",So the response must be the complete JSON object,other wise the same issue will be occur.

In your code,the response does not meets JSON format.

Example JSON

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

Simply copy the above code and paste in Page1.html and try now. [Note:Page1.html page contains only the above code]

Udhay
  • 31
  • 3
0

Do you have the ability to use server side language, such as PHP? You can use PHP to build your JSON output on page1. The only output on page1 should be the JSON, which is the correct way to retrieve the information from your AJAX request on page2.

When you make a call to another page via AJAX, it will not execute JS, this needs to be done server-side.

Bear 곰
  • 35
  • 1
  • 7
0

First you have a mistake on the first html page

    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"));

you forgot to add ) in the end of each push call

second thing is that when you are using ajax, you're asking the server, while in this case the server returns

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

ajax function take this as result and doesn't execute any javascript code and doesn't wait until ready event

The result of the first html page that you want to be returned is

[{"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"}]

if you just put this json string in yout first html page witout any html tag, everything will work fine

I suggest you to put a server side code like php or nodejs to return the result you need in json not pure javascript because it's a client side langage

Khalid
  • 4,392
  • 5
  • 23
  • 50
0

As @Rory McCrossan said, if you make the POST request you will only get the source code of the first page. But if you want the first page to generate a custom JSON and send back to the parent page then probably you can create a hidden iFrame. The iFrame will redirect to the first page and the first page will send a message back for the parent page using cross-document messaging.

You can try below the HTML codes. I haven't tested it so it may give some errors.

First HTML Page

<!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> 

Second HTML Page

<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>

Reference:-

Rahul Satal
  • 1,403
  • 2
  • 21
  • 44