Call php from javascript and return an array from php to Javascript function

后端 未结 9 1597
孤街浪徒
孤街浪徒 2020-12-03 13:22

I want to write a function in javascript which will call the Getfilename.php and Get the $filesArray that is return in javascript.

GetFilenme.php is another file and

相关标签:
9条回答
  • 2020-12-03 13:27

    This is assuming you download and include the jQuery javascript library:

    $(function() {
        $.get('getfilename.php', { dir : 'path/to/dir' }, function(data) {
            // you should now have a json encoded PHP array
            $.each(data, function(key, val) {
                alert('index ' + key + ' points to file ' + val);
            });
        }, 'json');
    });
    

    This should be your PHP (although very insecure):

    <?php
    $dir = $_REQUEST['dir'] ;
    
    $filesArray = array(); 
    $Counter = 0; 
    $files = scandir($dir); 
    
    foreach ($files as &$file) { 
        if ($file!='.' && $file!='..' ) { 
            $filesArray[$Counter] = $file; 
            echo $filesArray[$Counter].''; 
            $Counter++;
        }
    } 
    
    echo json_encode($filesArray); 
    ?>
    
    0 讨论(0)
  • 2020-12-03 13:29

    The PHP should be stored on a remote server and called using a scripted HTTP request. Read up on AJAX for details of how this works and how to perform such tasks.

    You can't just do it in a browser as JavaScript has no PHP interpreter and neither do most browsers, and so can't just run a PHP file to get output.

    0 讨论(0)
  • 2020-12-03 13:30

    Use an asynchronous HTTP request in the JavaScript to load the output of the PHP script.

    For example, using the Prototype framework's Ajax.Request, say you have an HTML element with id="notice" and you want to update that based on the script's output (a simple "true" or "false" string).

    new Ajax.Request('/validate.php', {
      method: 'get',
      onSuccess: function(transport) {
        var notice = $('notice');
        if (transport.responseText == 'true')
          notice.update('Validation successful');
        else
          notice.update('Validation failed');
      }
    });
    
    0 讨论(0)
  • 2020-12-03 13:35

    You should try JQuery. I send and receive from JS to PHP the following way, assuming this is the form.

    <div id="form"> 
    <input type="text" id="email" /><br /> 
    <button id="submit">Submit</button> 
    </div> 
    <div id="response"> 
    </div> <!-- load jquery --> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript" > </script>
    

    // put this in script type="text/javascript" tags
    $(document).ready(function(){
    var emailValue;
    
      $("#submit").click(function(){
      // when the user clicks the submit button
    
        // get the value of email and put it in the variable we made above
        emailValue=$("#email").val();
    
        /* am going to send a post variable called "email" 
        * with the value of "emailValue" to a script called receiver.php
        */
        $.post('receiver.php',{email:emailValue},function(e){
         // "e" is variable that contains the echoed string
         // check if it's true or false
      if(e=="true")
      alert ("valid email");
      else
      alert("invalid email");
        });
    
      });
    
    });
    

    receiver.php

    $email=$_POST['email'];
    
    // checkMail is a fictional function that returns a bool
    $valid=checkMail($email);
    
    if($valid)
    {
     // email is valid
     echo "true";
    }else{
     // email is invalid
     echo "false";
    }
    

    Note: if you are not sending data to the PHP script you should use $.get instead of $.post, it's a little bit faster.

    You can also use the JavaScript variable e and load its contents in the response division in your form like this

    $("#response").html(e);
    

    This would accomplish the same thing as if you used JQuery's load() function like Coder mentions below.

    0 讨论(0)
  • 2020-12-03 13:35

    If your not using a javascript framework like jquery or prototype then you will have to create a XMLHttpRequest object yourself which the javascript framework would normally wrap up. Something like the following:

    function GetHttpObject() 
    {
        if (typeof XMLHttpRequest != 'undefined')
            return new XMLHttpRequest();
    
        try 
        {
            return new ActiveXObject("Msxml2.XMLHTTP");
        } 
        catch (e) 
        {
            try 
            {
                return new ActiveXObject("Microsoft.XMLHTTP");
            } 
            catch (e) {}
        }
    
        return false;
    }
    
    0 讨论(0)
  • 2020-12-03 13:43

    If you're just using JavaScript, probably the simplest solution is to include that as a <script> tag.

    eg:

    <script src="Getfilename.php" type="text/javascript"></script>
    

    Then in your PHP, instead of:

    return $filesArray;
    

    have it write some JavaScript.

    echo "var result = ".json_encode($filesArray).";";
    

    Your $filesArray value will now be in your javascript as the variable result.

    <script>alert(result)</script>
    
    0 讨论(0)
提交回复
热议问题