简体   繁体   中英

Write a javascript Array to a json file on another domain

First of all i have the following to convert my Javascript array to a JSON array.

<script type="text/javascript" src="https://github.com/douglascrockford/JSON-js/blob/master/json2.js"></script>

  var sv_defaultArray = new Array([]);
  sv_defaultArray[0] = "post 4";
  sv_defaultArray[1] = "post 5";
  sv_defaultArray[2] = "post 6";

  var myJsonString = JSON.stringify(sv_defaultArray);

Now i would like to write the converted array to a json file lets say http://www.foobar.com/array.json via any conventional method possible.

So now i am at the following stage with php and jQuery.post facilities;

<?php
$list = $_POST["array"];
$fp = fopen('array.json', 'w');
fwrite($fp, $list);
fclose($fp);
?>

$.post("http://www.foobar.com/write.php", { 'array': myJsonString});

The above solution is giving me errors mainly returned in console as origin errors.

You can have a server side PHP file on the other domain accept your json as POST/GET paramter, and write it to a file, then return a json response as result.

Then you can use jquery.getJSON on your first domain to call the url with your json that needs to be written

http://api.jquery.com/jQuery.getJSON/

You need a server-side script that can write a file. Then you could send the json array to it through ajax and it will write the file.
I must stress the fact that javascript doesn't have access to the file-sistem, so it cannot be done with only pure javascript.

You will need to submit the data through a form as AJAX does not allow cross-domain requests. Everything else you are doing is 100% correct (assuming the php is on the destination server). I would recommend a text area with visibility:none style tag set. Use js to populate the textarea and submit the form using form.submit()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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