简体   繁体   中英

Passing JSON data from JavaScript using Ajax to PHP

I have the following JS:

window.onload = function() {
'use strict';
var ajax = getXMLHttpRequestObject();

ajax.onreadystatechange = function() {
    if ( ajax.readyState == 4 ) {
        if ( (ajax.status >= 200 && ajax.status < 300) || (ajax.status == 304) ) {
            var data = JSON.parse(ajax.responseText);
            var file = '';
            file += 'Original: ' + data['org'].file + '<br>';
            file += 'Processed: ' + data['pre'].file + '<br>';
            document.getElementById('output').innerHTML = file; 
        } else {
            document.getElementById('output').innerHTML = 'Error: ' + ajax.statusText;
        }
    }
};

document.getElementById('btn').onclick = function() {
    ajax.open('POST', 'resources/test.json', true);
    ajax.setRequestHeader('Content-Type', 'application/json');
    ajax.send(null);
};
};

I would like to pass the data from

data['org'].file

and

data['pre'].file

to PHP and have it echo out the value using the POST method. Please no jQuery solutions this needs to be strictly JavaScript.

Something like this:

<?php $data = $_POST['the_data']; echo $data; ?>

Here is the JSON from test.json:

{
"org": {
    "file": "css/original.css"
},
"pre": {
    "file": "css/preprocessed.css"
}
}

If you want a PHP script to echo JSON data, it's as simple as this:

<?
    $json = file_get_contents('php://input');
    //...
    echo $json;
?>

To post it from Javascript, I reccomend reading this . There's a reason so many people use jQuery...

have a look on JSON Stringify you can use that to encode your data.

Then after you encoded you can send it wherever you need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM