将javascript函数的结果发送给PHP

I'm trying to get the results of a javascript function to send to a PHP file.So I can use it as a PHP variable.

This is the function that I want to use in the PHP file:

function password()
{
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for( var i=0; i < 5; i++ )
        text += possible.charAt(Math.floor(Math.random() * possible.length));

    return text;


}

This is a Prototype (so I'm not worried about security risks)

Thanks.

UPDATE: Could someone please show me how a could submit this as a form?

You can use AJAX to send your value in php! :)

function password(){
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for( var i=0; i < 5; i++ )
        text += possible.charAt(Math.floor(Math.random() * possible.length));

    return text;


}

var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://www.yourSite.com/ajax.php');
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.addEventListener('readystatechange', function() {
            if (xhr.readyState === 4 && && xhr.status === 200) { 

                console.log(xhr.responseText);
            }
        }, false);
xhr.send('text=' + password());

Post send a data via form, so, we should add a content-type:

xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

Then in your php code: Just do this:

<?php echo $_POST['text']; ?>

To send data to your PHP program (which runs on your web server), you have to make the web browser (which runs your Javascript) make a HTTP request. The most common options are

  • submitting a form
  • making an Ajax request

You cannot pass your result from the javascript function to the PHP code... PHP code runs at the server side and javascript on the client side.

You have to make an AJAX call and send your results that way.

So, that function is being executed on the client, in Javascript? And you want the results of it available in your server-side PHP? I'd suggest fire an AJAX request, or submit a form.

If you are running this on a web server you should use GET, POST or Cookie method to share variable doing an HTTP request to sent them to a php script.