Javascript 如何检索变量而不是echo

Javascript 如何检索变量而不是echo,javascript,php,ajax,Javascript,Php,Ajax,我刚刚开始学习Ajax,想知道如何获取PHP变量而不是echoI ajax\u php\u 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('

我刚刚开始学习Ajax,想知道如何获取PHP变量而不是
echo
I

ajax\u php\u 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">
函数ajax\u post(){
var hr=新的XMLHttpRequest();
var url=“ajax\u php\u code.php”;
var fn=document.getElementById('first_name')。值;
var ln=document.getElementById('last_name')。值;
var vars=“firstname=“+fn+”&lastname=“+ln;
hr.open(“POST”,url,true);
hr.setRequestHeader(“内容类型”、“应用程序/x-www-form-urlencoded”);
hr.onreadystatechange=函数(){
如果(hr.readyState==4&&hr.status==200){
var return_data=hr.responseText;
document.getElementById('status').innerHTML=返回数据;
}
}
人力资源发送(vars);
document.getElementById('status').innerHTML=“处理…”;
}

这工作正常,但我希望发送一个变量而不是echo。可能吗?

是的,当然可能:

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

让脚本调用die($foobar)

你可以让你的剧本以这样的结尾:

标题('Content-Type:application/json')

骰子(json_编码($array))


以JSON格式传输数组。

通常的方法是让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

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

echo json\u encode(数组(“status”=>“success”,“message”=>“Your name is.”.$\u POST['firstname]”..$\u POST['lastname],“first\u name”=>$\u POST['firstname'],“last\u name”=>$\u POST['lastname]”)

hr.onreadystatechange函数中的更改代码

`风险值响应=评估(“+hr.responseText+”);//将响应转换为json 如果(response.status==“success”){

alert(response.message);//使用变量first\u name和last\u name&message将您输出
}`以JSON格式返回数据怎么样

然后在javascript中:

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

好的,我们这里有很多答案,让我告诉您一种我认为最好的方法,将用户名和密码等详细信息作为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>
用户名:
密码:
//显示输出或成功消息
$(“#提交”)。单击(函数(){
var user=$(“#username”).val();//从字段username获取值
var pass=$(“#password”).val();//同上
var obj={'username':用户,'password':pass};//创建普通对象
var json=json.stringify(obj);//转换为json字符串
console.log(obj);//仅用于检查输出
console.log(json);//同上
$.post('test.php',json,函数(响应){//send to your service file“tst.php,json
警报(响应);//查看服务器的响应
if(!response){//未接收数据的情况
$(“#输出”).html(“服务器没有响应,请重试”);
}
否则{
var data=JSON.parse(response);//转换为JSON对象
$(“#输出”).html(data.username);//访问接收到的数据
}
});
});
php在html正文中接收json,我们可以检索它,使用它检查身份验证和发送消息或响应代码

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

 ?> 
test.php

由于发送和接收的数据都是json,所以在AJax请求(abc.php)中写入“application/json”,并提及标题(“内容类型:application/json”)可以避免。

您可以使用JSON格式,在PHP脚本中回显JSON字符串,然后您可以在Javascript中解码该字符串以操作变量。@a-p为什么添加Youtube链接?OP确认他确实在遵循该教程吗?最重要的是,为什么编辑被批准?我回滚了Youtube视频编辑。好的,我们可能会将其移动到聊天室或meta,但如果OP从未将视频放在那里,也从未提及他正在关注该视频,那么为什么视频应该在那里?变量将可用于resposeWell您现在正在使用jquery,当它第一次使用纯javascript编写时。确实,jquery可以使用javascript编写相同的内容,但看看php文件如何处理删除从第一个文件发送的post请求中收到的数据。!!我没有质疑是否可能只是原始post是用javascript编写的。“这工作正常,但我希望发送一个变量,而不是echo。是否可能?“我写这个请求只是为了说明可以发送数据而不是echo,以及如何接收和使用它。”
test.php
 <?php
 $json = file_get_contents('php://input');
 $obj = json_decode($json);
 echo json_encode($obj);

 ?>