【问题标题】:How do i send form data to php using fetch in nativescript?如何使用 nativescript 中的 fetch 将表单数据发送到 php?
【发布时间】:2020-05-14 02:33:42
【问题描述】:

我正在尝试在我的 nativescript 应用程序中创建一个注册表单,我正在使用 fetch api 来发布数据。但现在它只是填充数据库而没有实际上传数据。这是我尝试过的

JS

const phpData = {
                email: "user@nativescript.org",
                password: "password",
                name: "Adekunle Adeyeye",
                number: "07019888741",
            }
            /*email = viewModel.getViewById("email").value;
            password = viewModel.getViewById("password").value;
            name = viewModel.getViewById("name").value;
            number = viewModel.getViewById("number").value;*/

            fetch("https://goodsbuy.000webhostapp.com/register.php", {
                method: 'POST',
                body: JSON.stringify(phpData),
                headers:{
                    "content-type": "application/json; charset=UTF-8"
                }
            })
            .then(response => response.json())
            .then(json => console.log(json))
            .then((phpData) => {
                console.log('Success:', phpData);
                this.set("processing", false);
                Toast.makeText("Successful").show();
                this.isLoggingIn = true;
              })
              .catch((error) => {
                console.error('Error:', error);
                this.set("processing", false);
                Toast.makeText("Account Already exists").show();
                this.isLoggingIn = false;
              });

PHP

$email = $_POST['email'];
$password = $_POST['password'];
$name = $_POST['name'];
$number = $_POST['number'];

$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
      $sql = "INSERT INTO comedyapp(`name`, `email`, `number`, `password`) VALUES ('$name', '$email', '$number', '$password')";
        if ($conn->query($sql) === TRUE) {
            echo '{"items":'. json_encode('Good') .'}'; 
        } else {
            echo '{"items":'. json_encode('Bad') .'}';
        }

请帮助我。

【问题讨论】:

  • 您对 SQL 注入持开放态度,应该立即解决
  • @treyBake 怎么样?仅据我所知。
  • 如果您在正文中将数据作为字符串化 json 传递,您可能需要使用:$data = file_get_contents('php://input'); 访问数据,然后运行 ​​$params = json_decode($data, true); 将 json 转换为数组。跨度>
  • @MuhammadTashfeen 阅读here :)
  • 感谢@MagnusEriksson

标签: php fetch nativescript fetch-api


【解决方案1】:

替换

$email = $_POST['email'];
$password = $_POST['password'];
$name = $_POST['name'];
$number = $_POST['number'];

extract(json_decode(file_get_contents('php://input'),true));

它会自动声明变量。

【讨论】:

  • 将数组作为一个数组保存在一个变量中比使用extract() 更好。特别是当数据来自前端时。
  • 是的,同意您的评论。会期待的。
  • 就像extract() 的文档所说:“警告不要对不可信的数据使用extract(),例如用户输入(例如$_GET、$_FILES)。”(包括发布数据)
  • 非常感谢@MagnusEriksson。一定会记住的。
猜你喜欢
  • 2020-02-04
  • 2018-10-08
  • 2022-01-16
  • 2018-01-04
  • 1970-01-01
  • 2019-06-06
  • 2014-01-20
  • 1970-01-01
  • 2020-10-11
相关资源
最近更新 更多