简体   繁体   中英

How can i parse php variable to my javascript function result?

I have a script, i have to parse javascript variable to PHP file, i've no problem with this function, in my console i can see that the username variable is sent, it's fine .

       $.post("user_add-js.php", { username: username })
                .done(function(data) {
                alert("Data Loaded: " + data);
                });

In my user_add-js.php file , i wrote the variable $data with a value but i can't return the value "test", the variable is empty . I guess i forgot to add something in my PHP code to parse the value from PHP to javascript .

<?php

$data = "test";

?>

you need to set the header

header('Content-type: application/json');

and also you have to encode the variable to json like this

echo json.encode($data);

once you get the result to javascript you should parse the json code

data = JSON.parse(data);

This solution helps you get you data from PHP in any format ( object, array, string ... )

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