简体   繁体   English

从JavaScript接收数据到PHP

[英]Receiving data from JavaScript into PHP

Working example below, hopefully this will help others learn! 下面的工作示例,希望这将有助于其他人学习!

I'm using AJAX in javascript to send a JSON string to PHP. 我在javascript中使用AJAX向PHP发送JSON字符串。

I'm not familiar with AJAX, javascript or php, so this is taking me a while to get started. 我不熟悉AJAX,javascript或php,所以这需要一段时间才能开始。

I have a html file with a username field, password field, and login button. 我有一个带有用户名字段,密码字段和登录按钮的html文件。

Then I have a javascript file that takes the username pass and sends it to a php file. 然后我有一个javascript文件,采用用户名传递并将其发送到PHP文件。

I know the php file is being accessed because I am seeing the test echo in console. 我知道正在访问php文件,因为我在控制台中看到了测试回显。

I just cant figure out how to access the data I'm sending to the php. 我只是想弄清楚如何访问我发送到PHP的数据。

script. 脚本。

function attemptLogin(){

var inputUserName = JSON.stringify(document.getElementById("userName").value);


var ajaxData = new XMLHttpRequest();
ajaxData.open('GET', 'ajax.php', true);
ajaxData.onreadystatechange = function(){

    var DONE = 4;
    var OK = 200;

    if (ajaxData.readyState === DONE) {
        if (ajaxData.status === OK) {
            console.log(ajaxData.responseText);
        }else{
            console.log("ERROR : " + ajaxData.status);
        }
    }
};
ajaxData.send(inputUserName);
}

ajax.php ajax.php

<?php
    echo"TestInPHP";
?>

For now all I want to do is echo the username back to console, I'm sure the syntax is something simple, I just cant figure out what it is. 现在我想做的就是将用户名回到控制台,我确信语法很简单,我只是想弄清楚它是什么。


Here is an edit for the working code thanks to SuperKevin in the comments below. 以下是评论中感谢SuperKevin的工作代码编辑。 This code will take the string in the username and password fields in HTML by the JS, send it to PHP and then sent back to the JS to output to the browser console window. 此代码将JS中的用户名和密码字段中的字符串作为字符串,将其发送到PHP,然后发送回JS以输出到浏览器控制台窗口。

index.html 的index.html

<input type="text" name="userID" id="userName" placeholder="UserID">
<input type="password" name="password" id = passW placeholder="Password">
<button type="button" id = "button" onclick="attemptLogin()">Click to Login</button>

script.js 的script.js

function attemptLogin(){

var inputUserName = 
JSON.stringify(document.getElementById("userName").value);
// console.log(inputUserName);
var inputPassword = JSON.stringify(document.getElementById("passW").value);

var cURL = 'ajax.php?fname='+inputUserName+'&pass='+inputPassword;


var ajaxData = new XMLHttpRequest();
ajaxData.open('GET', cURL, true);
ajaxData.onreadystatechange = function(){

    var DONE = 4;
    var OK = 200;

    if (ajaxData.readyState === DONE) {
        if (ajaxData.status === OK) {
            console.log(ajaxData.responseText);
        }else{
            console.log("ERROR : " + ajaxData.status);
        }
    }
};
ajaxData.send();
}

ajax.php ajax.php

<?php
  echo $_GET['fname']; 
  echo $_GET['pass'];
?>

Here's a simple example of how you would make a vanilla call. 这是一个如何进行香草调用的简单示例。

This is our main file, call it index.php . 这是我们的主文件,称之为index.php

<script>

    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("demo").innerHTML = this.responseText;
        }
    };
    xhttp.open("GET", "delete.php", true);
    xhttp.send();

</script>

Here's our server script. 这是我们的服务器脚本。 delete.php delete.php

<?php

echo "HELLO THERE"; 

Now, if you wanted to pass data to your script you can do the following: 现在,如果您想将数据传递到脚本,可以执行以下操作:

xhttp.open("GET", "delete.php?fname=Henry&lname=Ford", true);
xhttp.send();

To access this data you can use the global $_GET array in php. 要访问此数据,您可以在php中使用全局$_GET数组。 Which would look like this: 看起来像这样:

$fname = $_GET['fname']; 
$lname = $_GET['lname'];

Obviously, you have to sanitize the data, but that's the gist of it. 显然,你必须清理数据,但这是它的要点。

For a much more in depth tutorial visit W3Schools Tutorial PHP - AJAX . 有关更深入的教程,请访问W3Schools Tutorial PHP - AJAX

You can see all the data sent to your php with : 你可以看到发送到你的PHP的所有数据:

<?php
   print_r($_GET); //if it's send via the method GET
   print_r($_POST); //if it's send via the method POST
?>

So, in your case it will be something like : 所以,在你的情况下,它将是这样的:

<?php
  echo $_GET['username'];
?>

If you're not using jQuery then don't pay attention to my answer and stick to the pure javascript answers. 如果你不使用jQuery那么不要注意我的答案,并坚持纯javascript答案。

With jQuery you can do something like this: 使用jQuery,您可以执行以下操作:

First Page: 第一页:

$.ajax({
      url: 'sportsComparison.php',
      type: 'post',
      dataType: 'html',
      data: {
         BaseballNumber = 42,
         SoccerNumber = 10
      },
      success: function(data) {
        console.log(data);
      });

which will send the value 42 and 10 to sportsComparison.php with variable names BaseballNumber and SoccerNumber . 将发送值4210sportsComparison.php与变量名BaseballNumberSoccerNumber On the PHP page they can then be retrieved using POST (or GET if that's how they were sent originally), some calculations performed, and then sent back. PHP页面上,然后可以使用POST (或GET如果它们是最初发送的方式)检索它们,执行一些计算,然后发回。

sportsComparison.php: sportsComparison.php:

<?php
$BaseballValue = $_POST["BaseballNumber"];
$SoccerValue =  $_POST["SoccerNumber"];

$TotalValue = $BaseballValue * $SoccerValue;

print "<span class='TotalValue'>".$TotalValue."</span>";

?>

This will return a span tag with the class of TotalValue and the value of 420 and print it in the console. 这将返回具有TotalValue类和值420span标记,并在控制台中打印它。

Just a simple way to do ajax using jQuery . 只是一个使用jQueryajax的简单方法。 Don't forget commas in the parameter list. 不要忘记参数列表中的逗号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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