gpt4 book ai didi

javascript - 单击提交后,如何重定向到 js 组件并通过 php 将信息发送到 db?

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

单击提交 后,我被重定向到Home.js,没有任何问题,但没有信息未发送到数据库。

但是,如果我确实摆脱了重定向,那么数据将毫无问题地发送到数据库,但它不会将我重定向到 Home.js。相反,它将我重定向到 demo.php

目标:如何成功重定向到 Home.js(我现在就是)并同时将数据发送到数据库?

我做错了什么,我该如何解决?

这是 Login.js:

import React, { Component } from 'react';
import Home from "./Home";

class Login extends Component {
constructor(props) {
super(props);
this.state = {
redirect: false
};
this.nextPage = this.nextPage.bind(this);
}

nextPage(e) {
e.preventDefault();
this.setState({redirect: true});
}

render() {
const go = this.state.redirect;

if(go) return <Home/>;

return (
<div>
<form action="http://localhost/demo_react/api/demo.php" onSubmit={(e) => this.nextPage(e)} method={"POST"} encType="multipart/form-data">

<div className="form-group">
<label htmlFor="username">Email</label>
<input className="form-control" type="text" name="username"/>
</div>

<div className="form-group">
<label htmlFor="password">Password</label>
<input className="form-control" type="password" name="password"/>
</div>

<button className="btn btn-primary" value="Login" name={"submit"}>Submit</button>

</form>
</div>
);
}
}

export default Login;

这是demo.php:

$connection = mysqli_connect("localhost", "root", "", "loginapp");
$username = $_POST['username'];
$password = $_POST['password'];

if(isset($_POST['submit'])) {
$query = "INSERT INTO users(username, password) ";
$query .= " VALUES('$username', '$password')";

$result = mysqli_query($connection, $query);

if (!$result) {
die("Query failed" . mysqli_error($connection));
} else {
echo "Data send successfully to SQL";
}
}

最佳答案

当您调用 e.preventDefault() 时,您是在指示浏览器不要自动发送表单数据。相反,您必须自己执行该任务。

nextPage(e) 方法中,您应该抓取表单数据并向您的服务器执行 ajax POST 请求。您可能应该使用组件状态来存储任何用户输入。

这是您可以做到的一种方法。

export default class FormComponent extends Component {
state = {
name: "",
surname: ""
};

submitForm(e) {
e.preventDefault();

const formData = new FormData();
formData.append("json", JSON.stringify(this.state));

fetch("http://localhost/demo_react/api/demo.php", {
method: "POST",
body: formData
});
}

render() {
return (
<form action="post">
<div>
<label htmlFor="name">Name</label>
<input
name="name"
type="text"
value={this.state.name}
onChange={e => this.setState({ name: e.target.value })}
/>
</div>

<div>
<label htmlFor="surname">Surname</label>
<input
name="surname"
type="text"
value={this.state.surname}
onChange={e => this.setState({ surname: e.target.value })}
/>
<button type="submit" onClick={e => this.submitForm(e)}>
Submit
</button>
</div>
</form>
);
}
}

关于javascript - 单击提交后,如何重定向到 js 组件并通过 php 将信息发送到 db?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53696481/

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