簡體   English   中英

如何將 Post 請求發送到我反應的 php 文件?

[英]How to send Post request to a php file i react?

我是 reactjs 的新手。 我想知道如何向服務器(php 文件)發送 ajax 請求? 我的項目結構:在此處輸入圖片描述

src/index.js

import React from 'react';
import ReactDOM from 'react-dom';
class User extends React.Component{
constructor(){
    super();
    this.state={username:'someone'}
}
click_btn=()=>{
    var xhttp = new XMLHttpRequest();
    xhttp.open("POST", "insert.php", true);
    xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhttp.send("fname=Henry&lname=Ford");

}
render() {
    return(
        <div><h1>{this.state.username}</h1>
        <button type='button' onClick={this.click_btn}>show</button>
        </div>
    )
}
}

它返回狀態 404 和錯誤 Can not post insert.php。 我應該在哪里找到我的插入?php 或如何解決它?

制作一個 php 文件夾並將 php 文件移動到里面 - 這應該可以工作。

$.ajax({ 
    type:"POST",
    url:"php/insert.php",
    data: JSON.stringify(this.state), 
    contentType: 'application/json',
    success: function(res) {
        console.log(res);
        console.log("Added");
    }.bind(this),
    error: function(xhr, status, err) {
        console.error(xhr, status, err.toString());
    }.bind(this)
}); 

或者

fetch('php/insert.php', { // URL
    body: JSON.stringify(this.state), // data you send.
    cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
    headers: {
      'content-type': 'application/json'
    },
    method: 'POST', // *GET, POST, PUT, DELETE, etc.
    mode: 'cors', // no-cors, cors, *same-origin
    redirect: 'follow', // *manual, follow, error
    referrer: 'no-referrer', // *client, no-referrer
})
.then(function(response) {
    // manipulate response object
    // check status @ response.status etc.
    return response.json(); // parses json
})
.then(function(myJson) {
    // use parseed result
    console.log(myJson);
});

我應該在 PHP 服務器中找到 PHP 文件

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM