douju2053 2011-10-06 03:42
浏览 90

如何在PHP脚本编写XML文件后调用Javascript函数

I've got a PHP file with a SELECT statement in it that pulls data from a MySQL database. It then processes the data and writes the results to an XML file.

I've got a javascript file that uses the XML file. How do I call a javascript function, for example, doStuff(), after the PHP file has downloaded the data and written the XML file? I could call it after a setTimeout(), but I hope that there is a better way.

The XML file gets over-written each time the PHP script runs. So, the XML file may already exist.

Is there some event that I could have doStuff() fire after? Or a way of determining whether the PHP script has finished?

Any suggestions?

Thank you.


UPDATE:

Here's some more details on what I've got.

I've got a map with a form. When the users submits the form, I use Ajax to process the form. A PHP function is called and data from a MySQL database is selected. The data includes latitude and longitudes. The PHP file then writes an XML file with this data. The javascript file then reads the XML file and places markers on the map.

The PHP and the javascript work fine. The problem is that the javascript file fires immediately, as soon as the map loads. So, the data in the xml file (from a previous form selection) gets turned into markers. If I delete the xml file, then no markers are put on the map. The javascript tried to use the non-existent xml file as soon as it loads. It's not there, so no markers are placed on the map. And this is before the user has made any selections in the form.

I need some way to have the javascript function that loads the XML file do so only after the XML file has been written.

I'm follwing this tutorial . I've had to adapt it in order for it to work in a WordPress plugin.

In my PHP, I've got:

//Creates XML
//each marker has a lat and long
$my_xml ='<?xml version="1.0" ?>';
$my_xml .= '<markers>';

foreach($csf_data as $incident) {
    $my_xml .='<marker lat="'. $incident->latitude.'" lng="'.$incident->longitude.'" type="resto" />'; 
}

$my_xml .= '</markers>';

//Creates the XML file 
//(I've hardcoded markers.xml's path for now-- will change later)
$file_handle = fopen('/Users/myname/Sites/mysite/wp-content/plugins/myplugin/markers.xml', 'w');
fwrite($file_handle, $my_xml);
fclose($file_handle);

In the javascript, I've got:

function downloadUrl(url,callback) {

 var request = window.ActiveXObject ?
     new ActiveXObject('Microsoft.XMLHTTP') :
     new XMLHttpRequest;

 request.onreadystatechange = function() {

   if (request.readyState == 4) {
     request.onreadystatechange = doNothing;
     callback(request, request.status);
   }
 };

 request.open('GET', url, true);
 request.send(null);

}


var customIcons = {
  resto: {
    icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png',
    shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
  },
  bar: {
    icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png',
    shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
  }
};


downloadUrl("http://mysite/wp-content/plugins/myplugin/markers.xml", function(data) {
 var xml = data.responseXML;

  var markers = xml.documentElement.getElementsByTagName("marker");

  for (var i = 0; i < markers.length; i++) {
    var type = markers[i].getAttribute("type");
    var point = new google.maps.LatLng(
        parseFloat(markers[i].getAttribute("lat")),
        parseFloat(markers[i].getAttribute("lng")));
   
    var icon = customIcons[type];
    var marker = new google.maps.Marker({
      map: map,
      position: point,
      icon: icon.icon,
      shadow: icon.shadow
    });

 
  }});



function doNothing() {}

This code works, but I need these javascript functions to run only after PHP has written a new XML file. How can I call this javascript after the new XML file has been written?

Thank you.

  • 写回答

3条回答 默认 最新

  • dongyuxin5353 2011-10-06 07:20
    关注

    You can do it easilly, (not all required things like taking action if file cannot be created etc.. are taken care but main functionality is here) like this with these 2 files:

    <html>
    <head>
    <script type="text/javascript">
    
    var sq="'"; 
    var dbq="\"";
    var request = false;
    try { 
      request = new XMLHttpRequest(); 
    } catch (trymicrosoft) {                         
      try { 
        request = new ActiveXObject("Msxml2.XMLHTTP"); 
      } catch (othermicrosoft) {
        try {
          request = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (failed) {                  
          request = false;       
        }
      }
    }
    
    
    if (!request) 
      alert("Error initializing XMLHttpRequest!"); 
    </script>
    
    <script type="text/javascript">
    
       function makeFile( ) 
       {    
            var url = "createXml.php";  
            var params = "makeFile=1&limit="+document.getElementById('select').value+"";
            request.open("POST", url, true);  
    
            //Some http headers must be set along with any POST request.
            request.setRequestHeader("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
            request.setRequestHeader("Content-length", params.length);
            request.setRequestHeader("Connection", "close");
    
            request.onreadystatechange = updatePage;
            request.send(params);
    
       }////////////////////
    
          //You're looking for a status code of 200 which simply means okay.
       function updatePage() {
         if (request.readyState == 4) {
           if (request.status == 200) 
           {    
                //run the js created by php
                eval(request.responseText);  
                //get tha needed info
                document.getElementById('divResults').innerHTML=response[0]+
                '<input type='+dbq+'submit'+dbq+' value='+dbq+'Get it..'+dbq+
                ' onclick='+dbq+'getXmlFile('+sq+response[1]+sq+')'+dbq+'; >' ; 
           } 
           else{
             //alert("status is " + request.status);
             }
         }
       }//////////////////////////////////////////////////////////////////
    
    
       function getXmlFile(fileName) 
       {  
            var url = fileName; 
            var params = null; 
            request.open("POST", url, true);     
            request.setRequestHeader("Connection", "close");    
            request.onreadystatechange = displayFile;
            request.send(params); 
       }////////////////////
    
    
    
          function displayFile() {
         if (request.readyState == 4) {
           if (request.status == 200) 
           {    
                document.getElementById('textareaResults').innerHTML=request.responseText;
                document.getElementById('divResults').innerHTML=
                'File loaded in text area below. '+
                '<font size=1>You could also load these data directly to a js variable using php '+
                'without creating a file...</font>' ;
    
    
           } 
           else{
             //alert("status is " + request.status);
             }
         }
       }
    
    </script>
    </head>
    <body >
    
    
    How many records from Mysql to put into XML file? <br>
    <font size=2>(This is just for testing...)</font> <br> <br>
    <select id="select">
      <option value="10">10</option>
      <option value="20">20</option>
      <option value="30">30</option>
      <option value="40">40</option>
    </select> <span style="background-color:red;color:yellow;border: 5px solid gray;"  
    onClick="makeFile( )"/> Click To Go.. </span>
    
    <br> <br>
    <div    id="divResults">Thank you!</div>
    
    
    <textarea rows="10" cols="88"  id="textareaResults">
    </textarea>
    
    
    
    </pre>
    </body>
    </html>
    

    and the other one

    <?PHP 
    /**
    Mysql
    */
    mysql_connect('localhost', 'root',''); 
    mysql_select_db("mysql"); 
    $query="select * from help_category limit ".$_POST['limit'].";";  
    $resultID = mysql_query($query ) or die("Data not found."); 
    
    $xml_output = "<?xml version=\"1.0\"?>
    "; 
    $xml_output .= "<records>
    "; 
    
    for($x = 0 ; $x < mysql_num_rows($resultID) ; $x++){ 
        $row = mysql_fetch_assoc($resultID); 
        $xml_output .= "\t<record>
    "; 
        $xml_output .= "\t\t<help_category_id>" . $row['help_category_id'] . "</help_category_id>
    ";  
        $xml_output .= "\t\t<name>" . $row['name'] . "</name>
    ";  
        $xml_output .= "\t\t<parent_category_id>" . $row['parent_category_id'] . "</parent_category_id>
    "; 
        $xml_output .= "\t</record>
    "; 
    } 
    
    $xml_output .= "</records>"; 
    
    /**If an xml file wanted or not
    */
    if($_POST['makeFile']==1)
    {
        $dbq="\"";
        //same queries will make the same file name
        $fileName=md5($query).'.xml';
        //check if the file exists
        if(!file_exists($fileName))
        {
            //create a new file for writing
            $fp = fopen($fileName, 'w');
            fwrite($fp,  $xml_output); 
            fclose($fp);
            echo "var response = new Array( ); response[0]=".$dbq.'A new file created..'.$dbq.";  
            response[1]=".$dbq.$fileName.$dbq.";   ";
        }
        else
        {   
            echo "var response = new Array( ); response[0]=".$dbq.'File exists and waiting..'.$dbq.";  
            response[1]=".$dbq.$fileName.$dbq.";   ";
        }
    }
    /**If results are required directly to the page send them
    */
    else
        echo 
            $xml_output;
    
    ?> 
    

    NOTICE The aim of this script is to show in a fast way how can be done these things this guy asks. Down voting this answear (as has happened before -and not only to me-) for sql injections die function etc is in my opinion totally unproductive (security is not what the question asks!), the asker must be able to separate what code is for answearing his question and what is to help the answear get ready to run and test. For example the simple mysql with dies will make it easy to run the answear immediately. Sorry for this but unfortunately we have to make clear some very basic foundamentals some times!

    评论

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用