开发者

Write a javascript Array to a json file on another domain

开发者 https://www.devze.com 2023-03-30 02:19 出处:网络
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\"></

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 giv开发者_如何转开发ing 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()

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号