简体   繁体   English

通过XmlHttpRequest将数据从JS传递到PHP

[英]Pass data from JS to PHP via XmlHttpRequest

I'm confronting now with a problem, which consists in sending a JS object to PHP, and I found that it should be done via HtmlHttpRequest , but the problem is that I'm a novice in PHP,and furthermore, I do not understand very well how this XmlHttpRequest works. 我现在遇到一个问题,该问题包括向PHP发送一个JS对象,我发现应该通过HtmlHttpRequest完成,但问题是我是PHP的新手,而且我不理解XmlHttpRequest工作原理非常好。 I've tried different methods but, the one which I found suitable for me, returns constantly the same error. 我尝试了不同的方法,但是我发现适合自己的方法不断返回相同的错误。 The code will be posted below, and now about the problem, I canperform this request, but when I perform this, the PHP side returns me an error message that there exists an undefined index. 该代码将在下面发布,现在关于该问题,我可以执行此请求,但是当我执行此操作时,PHP端会向我返回一条错误消息,指出存在未定义的索引。

And here's the desired code 这是所需的代码

JS part : JS部分:

function createTransaction() {
    var xmlhttp = new XMLHttpRequest();
    var newTransaction = {"name": document.getElementById('wallets').value}
    newTransaction.data = {
        "transactionID": document.getElementById('trans-id').value,
        "time": document.getElementById('creation-time').value,
        "senders": getSenders(),
        "receivers": getReceivers(),
        "finalSum": setSum()
    };
    xmlhttp.open('POST', '/admin.php', true);
    xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    xmlhttp.onreadystatechange = function () {
        if (this.readyState === 4 || this.status === 200) {
            console.log(this.responseText); // echo from php
        }
    };
    xmlhttp.send({newTransaction});
    console.log(JSON.stringify(newTransaction));
}

A short description : In this function I'm generating a an object, then send to PHP via XmlHttpRequest using a POST request, that's all, on the PHP side there's a variable which catches this request and echoes it. 简短说明:在此函数中,我生成一个对象,然后使用POST请求通过XmlHttpRequest发送到PHP,就是这样,在PHP端,有一个变量捕获该请求并回显它。 Here's the code : 这是代码:

$newTransaction = $_POST['newTransaction'];
echo $newTransaction;

What is wrong and/or how it should be better to resolve this issue? 有什么问题和/或应该如何更好地解决此问题?

You are doing two things wrong. 您做错了两件事。

  1. You are not converting your object to JSON before you send it: xmlhttp.send(JSON.stringify({newTransaction})); 在发送对象之前,您不会将其转换为JSON: xmlhttp.send(JSON.stringify({newTransaction})); . Instead you are sending the default string representation of an object: "[object Object]" which isn't helpful. 相反,您发送的是对象的默认字符串表示形式: "[object Object]" ,它没有帮助。
  2. Your PHP is expecting to receive URL encoded or Multipart form data. 您的PHP希望接收URL编码或Multipart表单数据。 It is not expecting to receive JSON. 它不希望接收JSON。 See this answer 看到这个答案

An XmlHttpRequest or Ajax for short is a requests that will not reload the page, with this logic you are sending a POST request like you would do in a form, when you send a form, you're sending a pair key : values to the file you're sending lets say you have a form like this 简称XmlHttpRequestAjax是不会重新加载页面的请求,通过这种逻辑,您将像在表单中一样发送POST请求,当您发送表单时,您将在发送对key : values您要发送的文件可以说您具有这样的形式

<input name="transactionID">
<input name="time">
<input name="senders">
<input name="receivers">
<input name="finalSum">

the values will be received like this in the global $_POST array 将会在全局$_POST数组中像这样接收值

{
    "transactionID": "some id",
    "time": "some time",
    "senders": "some senders",
    "receivers": "some receivers",
    "finalSum": "final sum"
}

when you do a Ajax request, you do the same but without the inputs html , when you send the data like this 当您发送Ajax请求时,您执行相同的操作,但是没有inputs html ,当您发送这样的数据时

newTransaction.data = {
    "transactionID": document.getElementById('trans-id').value,
    "time": document.getElementById('creation-time').value,
    "senders": getSenders(),
    "receivers": getReceivers(),
    "finalSum": setSum()
};
xmlhttp.send({newTransaction});

In your admin.php you will receive something like 在您的admin.php您将收到类似

{
    "data" : {
        {
            "transactionID": "some id",
            "time": "some time",
            "senders": "some senders",
            "receivers": "some receivers",
            "finalSum": "final sum"
        }
    }
}

I recommend you 2 thigns 我建议你2个

  1. in your admin.php use echo var_dump($_POST);die(); 在您的admin.php中使用echo var_dump($_POST);die(); to see exactly what are you receiving 看看你到底收到了什么
  2. use a plugin to perform the ajax call like jQuery, axios, etc. this will give you tools to better handling the request and responses. 使用插件执行jQuery,axios等ajax调用。这将为您提供更好地处理请求和响应的工具。

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

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