gpt4 book ai didi

javascript - 如何将数组发送到 PHP 文件,以便可以使用 HTTP 请求将值添加到 mySQL?

转载 作者:行者123 更新时间:2023-11-29 23:48:25 25 4
gpt4 key购买 nike

将 javaScript 数组发送到 PHP 文件,然后将元素存储在 mySQL 数据库中。

目前,我的“httpSend.responseText”警报出现错误。声明通知:未定义索引:名称位于 .. 第 8 行

注意:未定义索引:第 9 行 .. 中的地址

警告:mysqli_query() 期望参数 1 为 mysqli,第 12 行 .. 中给出的资源

我不确定数组是否正确发送或正确接收。

var name = "John";
var address = "UK";

var sendInfo = {
Name: name,
Address: address
};

var httpSend = new XMLHttpRequest();
var php = "http://server/~name/folder/insertOffer.php";
httpSend.open("POST", php, true);

httpSend.onreadystatechange = function() {//Call a function when the state changes.
if(httpSend.readyState == 4 && httpSend.status == 200) {
alert(httpSend.responseText);
}
}

httpSend.send(sendInfo);

PHP

 <?php

include("mysqlconnect.php");


$name = $_POST['name'];
$address = $_POST['address'];


mysqli_query($connection,"INSERT INTO offerSelected (Id, Url) VALUES ('$name', '$address')");
?>

mysqlconnect 看起来像这样

<?php
$connection = mysql_connect("localhost", "user", "pass");

if(!$connection){
die('Could not connect to server: ' . mysql_error());
}

mysql_select_db("database", $connection);
?>

最佳答案

试试这个:

var name = "John";
var address = "UK";

var sendInfo = {
Name: name,
Address: address
};

var params = "sendInfo=" + JSON.stringify(sendInfo);

var httpSend = new XMLHttpRequest();
var php = "http://server/~name/folder/insertOffer.php";
httpSend.open("POST", php, true);

httpSend.onreadystatechange = function() {//Call a function when the state changes.
if(httpSend.readyState == 4 && httpSend.status == 200) {
alert(httpSend.responseText);
}
}

httpSend.send(params);

PHP 代码:

<?php

include("mysqlconnect.php");

$sendInfo = json_decode($_POST['sendInfo']);

$name = $sendInfo ['name'];
$address = $sendInfo ['address'];


mysqli_query($connection,"INSERT INTO offerSelected (Id, Url) VALUES ('$name', '$address')");
?>

关于javascript - 如何将数组发送到 PHP 文件,以便可以使用 HTTP 请求将值添加到 mySQL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25788334/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com