Passing a Javascript string to PHP

后端 未结 4 888
傲寒
傲寒 2021-01-20 08:21

i want to pass a javascript string to php ... WHICH is RIGHT after the code .. in the script.



        
4条回答
  •  囚心锁ツ
    2021-01-20 08:40

    When someone visits a website, this is generally what happens:

    1. Their browser sends a request to the server.
    2. The server evaluates that request.
    3. The server realizes, "Egad, the page they're requesting has PHP!"
    4. The server evaluates the PHP, and only sends the results to the browser.
    5. The browser parses the content that it receives.
    6. The browser realizes, "Egad, the page I received has JavaScript!"
    7. The browser evaluates the JavaScript, entirely on the client's machine.

    So PHP and JavaScript are basically at different ends of the process. Only the server handles PHP, and only the client handles JavaScript.

    To "give" a string to PHP, you'd have to make a request of the PHP page, sending that string as a GET variable:

    http://www.yourdomain.com/some_php_page.php?myvar=mytext
    

    There are a few ways to do this with JavaScript.

    1. If you only care about making that request on the PHP page, and you don't need to worry about receiving any information back, you can just create an image and use the URL as the source:

      var fakeImg = new Image();
      fakeImg.src = 'http://www.yourdomain.com/some_php_page.php?myvar=mytext';
      

      Even though you're requesting an image, the server doesn't know that, and will process your request by calling the PHP evaluating it, etc.

    2. You can make an actual AJAX request. Start by creating an XMLHttpRequest object:

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

      There are some issues in IE with cached responses on AJAX requests, so make the url unique:

      var url = 'http://www.yourdomain.com/some_php_page.php?myvar=mytext&unique=whatever';
      

      Tell your XHR where you want it to go, and how you want it to get there:

      xhr.open('GET', url, true);
      // The "true" parameter tells it that we want this to be asynchronous
      

      Set up a method that will check for when a response is received:

      xhr.onreadystatechange = function () {
          if (xhr.readyState === 4 && xhr.status < 400) {
              success(xhr.responseText);
          }
      };
      

      And finally, send the request:

      xhr.send(null);
      // We set "null" because some browsers are pissy
      

      Some notes to keep in mind:

      • You have to build the success function yourself, to handle the string that your PHP page will return.
      • You can pass that function xhr.responseXML if you want, but that's usually just a hassle for me.
      • Using onreadystatechange the way I have will (I believe) introduce memory leaks in some versions of IE

提交回复
热议问题