如何检索变量而不是echo


how to retrieve variable instead of echo

我刚刚开始学习Ajax,想知道如何获得一个PHP变量,而不是echo,我遵循这个

ajax_php_code.php

echo 'Your name is '.$_POST['firstname'].''$_POST['lastname].'';

html/ajax

function ajax_post(){
var hr = new XMLHttpRequest ();
var url = "ajax_php_code.php";
var fn = document.getElementById('first_name').value;
var ln = document.getElementById('last_name').value;
var vars = "firstname="+fn+"&lastname="+ln;
hr.open("POST", url, true);
hr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function(){
    if(hr.readyState == 4 && hr.status == 200){
        var return_data = hr.responseText;
        document.getElementById('status').innerHTML = return_data;
    }
}
hr.send(vars);
document.getElementById('status').innerHTML = "processing...";
}
<input type="text" id="first_name" name="first_name" placeholder="Namn"  />
<input type="text" id="last_name" name="last_name" placeholder="Efternamn"  />
<input type="submit" value="Skicka data" id="knapp" />
<div id="status">

这工作得很好,但我想有一个变量发送而不是echo是可能的吗?

通常的方法是让PHP返回JSON,然后在客户端解析JSON。

例如,在PHP中:

$data = array(
    firstname => $_POST['firstname'],
    lastname =>  $_POST['lastname']
);
header("Content-Type", "application/json");
echo json_encode($data);

然后是客户端,在ajax成功函数中:

var data = JSON.parse(hr.responseText);
// Now you can use data.firstname and data.lastname

让你的脚本调用死亡($foobar)。

你可以让你的脚本像这样结束:

头("application/json - type:");

die(json_encode($array))

如何将数据作为JSON返回。

$data = array(
    'firstname' => filter_input(INPUT_POST, 'firstname', FILTER_SANITIZE_STRING),
    'lastname' => filter_input(INPUT_POST, 'lastname', FILTER_SANITIZE_STRING)
);
header('Content-Type: application/json');
echo json_encode($data);
die();

在javascript中:

if(hr.readyState == 4 && hr.status == 200){
    var jsonObj = JSON.parse(hr.responseText);
    alert("My name is " + jsonObj.firstname + " " + jsonObj.lastname);
}

您可以创建json web服务,而不是返回直接输出

echo json_encode(array("status"=>"success","message"=>"Your name is ".$_POST['firstname']." ".$_POST['lastname],"first_name"=>$_POST['firstname'],"last_name"=>$_POST['lastname']));

更改hr中的代码。的onreadystatechange函数

' var response = eval("(" + hr。responseText + ")");//将响应转换为json如果响应。状态== "success"){

alert(response.message);//使用变量first_name和last_name &消息} '

是的,当然是可能的:

<?php
    header('Content-Type: application/json');
    $your_variable='value';
    echo json_encode($your_variable);
?>

我们这里有很多答案,让我告诉你一种我认为最好的方式,将用户名和密码等详细信息作为AJAX请求发送到服务器,并将结果发送回来。

下面是HTML/php文件的简单字段比如abc.php:

<label for="username">Username:</label>
<input type="text" id="username" name="username" placeholder="Enter Username" />
<label for="password">Password:</label>
<input type="password" name="password" id="password" placeholder="Enter Password" />
<input type="button" id="submit" value="Submit">
<div id="output"></div> //Shows the output or the success message 
<script>
 $("#submit").click(function() {
    var user = $("#username").val();           //Get the value from field username
    var pass = $("#password").val();            // same as above
    var obj = {'username': user, 'password': pass};               // create a plain object
    var json = JSON.stringify(obj);              // convert to JSON string
    console.log(obj);  //Just for checking the output
    console.log(json); //same as above
    $.post('test.php', json ,function(response) {              //send to your service file "tst.php, the JSON
        alert(response);                     //see the response from the server
        if(!response) {                     //cases where data is not received
            $("#output").html("Server Not Responding, Please Try Again");
        }
        else {
            var data = JSON.parse(response);              //convert to JSON object
            $("#output").html(data.username);             //access the data received

        }
    });
});
 </script>

test.php接收html主体内的json,我们可以检索它,用它来检查身份验证和发送消息或响应代码。这里我把同样的obj发回

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

由于发送和接收的数据都是json,所以在AJax请求(abc.php)中编写"application/json"并提及标题("content-type: application/json")可以避免