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

后端 未结 9 1598
孤街浪徒
孤街浪徒 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:45

    You can get it easily by ajax. Even you can use Jquery to post the value to php and get the ajax response within a single line of code like below.

    p['value']=2;//some input value to be posted
    $('#data').load('http://example.com/validator.php',p,function(str){}    );
    

    html:

    <div id="data">
    </div>
    

    In this piece of code you are posting p['value'] as 2 to the validator.php and getting the response and load that value to data div in the same page.

    In our php code //get the posted value into some $value and

    if($value==2)
    echo 'true I got 2'
    else
    echo 'I didnot got 2 You posted wrong value';
    

    This will print true I got 2 in the div #data. This may not be your exact requirement but its very helpful.

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

    At the end, do this:

    print json_encode($filesArray);
    

    and it will send back a json object, which Javascript can read easily.

    0 讨论(0)
  • 2020-12-03 13:53
    function GetXmlHttpObject()
    {
    if (window.XMLHttpRequest)
      {
      // code for IE7+, Firefox, Chrome, Opera, Safari
      return new XMLHttpRequest();
      }
    if (window.ActiveXObject)
      {
      // code for IE6, IE5
      return new ActiveXObject("Microsoft.XMLHTTP");
      }
    return null;
    }
    
    function CallSomePHP(username, password)
    {
        xmlhttp=GetXmlHttpObject();
        if (xmlhttp==null)
        {
        alert ("Browser does not support HTTP Request");
        return;
        }
        var url="myPhp.php";
        url = url+"?username="+username+"&password="+password;
        xmlhttp.onreadystatechange=stateChanged;
        xmlhttp.open("GET",url,true);
        xmlhttp.send(null);
    }
    
    function stateChanged()
    {
        if (xmlhttp.readyState==4)
        {
            alert(xmlhttp.responseText); // this will alert "true";
        }
    }
    

    myphp.php

    <?
      // Get the values of username and password
      $username = $_GET['username'];
      $password = $_GET['password'];
      echo"true";
    ?>
    
    0 讨论(0)
提交回复
热议问题