简体   繁体   中英

assign a url output to a variable in javascript

The below code works well. I am new to ajax. Need is to assign the output of a url call like ' http://test.com/test.php ' to the variable json3 at line 6. The output of the url call looks like { "inp1:val1": { "data": [ [ 1378267200000, 0.0743 ], [ 1378270800000, 0.1787 ] ] }}

Currently I have this hard coded like this var json3 = { "inp1:val1": { "data": [ [ 1378267200000, 0.0743 ], [ 1378270800000, 0.1787 ] ] }}

 <html>
    <head>
    <title>JSON to CSV</title>
    <script src="json.js" type="text/javascript"></script>
    <script type="text/javascript">

    var json3 = { "inp1:val1": { "data": [ [ 1378267200000, 0.0743 ], [ 1378270800000, 0.1787 ] ] }}
    DownloadJSON2CSV(json3["inp1:val1"].data);

    function DownloadJSON2CSV(objArray)
    {
        var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;

        var str = '';

        for (var i = 0; i < array.length; i++) {
            var line = '';

            for (var index in array[i]) {
                line += array[i][index] + ',';
            }

            line.slice(0,line.Length-1); 

            str += line + '\r\n';
        }
        window.open( "data:text/csv;charset=utf-8," + escape(str))
    }

    </script>

   </head>
   <body>
    <h1>This page downloads csv....</h1>
</body>
</html>

Thanks for your help

You can give this try,

<script type="text/javascript">

var xmlhttp;
var txt,x,i,json3;
if (window.XMLHttpRequest)
  {
  // code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {
  // code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    json3 = eval(xmlhttp.responseText);
    DownloadJSON2CSV(json3["inp1:val1"].data);
  }
xmlhttp.open("GET","http://test.com/test.php",true);
xmlhttp.send();
}

function DownloadJSON2CSV(objArray)
{
    var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;

    var str = '';

    for (var i = 0; i < array.length; i++) {
        var line = '';

        for (var index in array[i]) {
            line += array[i][index] + ',';
        }

        line.slice(0,line.Length-1); 

        str += line + '\r\n';
    }
    window.open( "data:text/csv;charset=utf-8," + escape(str))
}

</script>

Let me know.

I see this more as a design decision other than the method to have this fulfilled.

  1. If the data is supposed to exist on the page right when it is loaded , and provided you have a dynamic back-end you're able to query (some back-end language that formats and return the page's HTML), it would be wise to have that variable populated immediately when the page is loaded.

  2. If you need to really query for that data and something is supposed to be done with it when the page is loaded, force the ajax call when the page initializes by inserting the ajax call at the beginning of your HTML (after any libraries are loaded and when it makes sense to have a script tag. Initialize the variable ( json3 ) that will be made available on the global context before the call is made.

  3. If something is supposed to happen after the variable is assigned a value, adopt an asynchronous callback, that will be invoked when the ajax call is finished:

      function doAjaxCall(callback) { //your ajax call here //and within your ajax success/failure handler: callback(value); } //your callback function function myCallback(value) { //do something with value here, such as alert(value); } //and invoke it with doAjaxCall(myCallback); 

The main point to my suggestions is to embrace the fact that you won't know when the variable is assigned a value unless you're able to cope with the asynchronous nature of the Ajax calls (exactly what the A stands for in Ajax).

It's also important to suggest the use of jQuery (or any other library) to make your life easier if you're not already using any.

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