问题
I know this question was asked many times, but after reading the answers, and trying some solutions, my code still doesn't work. Here are my working files :
my_app
-index.html
-task1
-index.html
In my_app/index.html, I declare an array , that I have to send to task1/index.html
testArray =[1, 2, 3];
var myUrl= "task1/index.html";
$.ajax({
type: "POST",
url: myUrl,
dataType: "json",
data: JSON.stringify({images:testArray}),
success: function (data) {
console.log('success');
alert(data);
}
});
window.open(myUrl);
//this code is called when a radio button is checked
The new window which points to the right url opens, but the testArray isn't sent. I got 2 errors:
1/ Origin null is not allowed by Access-Control-Allow-Origin.
2/the variable images is not defined when I try to access it from task1/index.html
For the 1st error, I read that this may be caused by Google Chrome's restriction when it comes to use Ajax with local resources. As suggested here Origin null is not allowed by Access-Control-Allow-Origin, I added
--allow-file-access-from-files
in Google Chrome properties. But the path was not accepted (I had a pop-up window "path not correct").
What is weird is that I tried to run the code with FireFox, I still have error 2
Is anything missing in my Post Ajax request? Is it possible to use Ajax to send data between 2 html files ?(I don't have any client/server side app here)
Thanks!
回答1:
If you need to send the data to a new window that you are going to open in that moment, use GET instead and pass the parameters on the url.
But, you could create an empty window first, then do your ajax and use the return content to fill your new window.
Here is an example fiddle opening the window and filling it with the result of a POST call: http://jsfiddle.net/bxhgr/
var mywindow = window.open();
testArray = [1, 2, 3];
var myUrl = "/echo/json/";
$.ajax({
type: "POST",
url: myUrl,
dataType: "json",
data: {
json: JSON.stringify({
images: testArray
})
},
success: function (data) {
console.log('success');
//alert(data);
mywindow.document.body.innerHTML = '<pre>' + data.images + '</pre>';
}
});
来源:https://stackoverflow.com/questions/18216447/passing-data-from-an-html-page-to-another-in-javascript