ปัญหาเกี่ยวกับคำขอ POST ในการตอบสนอง
Aug 16 2020
การคลิกปุ่มใช้งานได้เนื่องจากฉันเห็นบันทึก แต่คำขอ POST ไม่เกิดขึ้น ฉันได้สร้างช่องป้อนข้อมูลอย่างง่ายแล้วและเมื่อคลิกปุ่มก็ควรส่งคำขอ POST ไปยังเซิร์ฟเวอร์
ฉันคิดไม่ออกว่าทำไมคำขอ POST จึงไม่เกิดขึ้นดังนั้นโปรดช่วยฉันหาวิธีแก้ปัญหา
ความคิดเห็น js:
import React from 'react';
export class Comment extends React.Component {
constructor(props){
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
//SEND POST request
console.log('handling click');
const xhr = new XMLHttpRequest();
const URL = "http://localhost:8080/api/comments"
xhr.onreadystatechange = () => {
if(xhr.readyState === XMLHttpRequest.DONE){
console.log('POST request sent, comment posted.')
}
xhr.open('POST',URL);
xhr.setRequestHeader('Content-type', 'text/plain');
xhr.send(document.getElementById('comment-box').value);
}
}
render(){
const comment_form = (
<div className="posts">
<input type="text" id="comment-box" name="comment" placeholder="Say something nice." />
<button className="submit-button" type="button" onClick={this.handleClick}> Comment </button>
</div>
);
return comment_form;
}
}
คำตอบ
3 Asutosh Aug 16 2020 at 03:40
คุณมีข้อผิดพลาดทางไวยากรณ์เช่นปิด} ของ onReadyState eventhandler ไม่ถูกที่
import React from "react";
import "./styles.css";
export class Comment extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
//SEND POST request
console.log("handling click");
const xhr = new XMLHttpRequest();
const URL = "http://localhost:8080/api/comments";
xhr.onreadystatechange = () => {
if (xhr.readyState === XMLHttpRequest.DONE) {
console.log("POST request sent, comment posted.");
}
};
xhr.open("POST", URL);
xhr.setRequestHeader("Content-type", "text/plain");
console.log(document.getElementById("comment-box").value);
xhr.send(document.getElementById("comment-box").value);
}
render() {
const comment_form = ( <
div className = "posts" >
<
input type = "text"
id = "comment-box"
name = "comment"
placeholder = "Say something nice." /
>
<
button className = "submit-button"
type = "button"
onClick = {
this.handleClick
} >
{
" "
}
Comment {
" "
} <
/button> <
/div>
);
return comment_form;
}
}
1 StarkJeon Aug 16 2020 at 03:32
ตอบ
ลูกศรฟังก์ชั่นการผูกthis
และเรียกกลับ onreadystatechange this === Comment
ถูกเรียกเมื่อ ดังนั้น xhr.onreadystatechange ไม่ทำงาน
xhr.onreadystatechange = function() {
if(xhr.readyState === XMLHttpRequest.DONE){
console.log('POST request sent, comment posted.')
}
ฉันคิดว่าข้อมูลอ้างอิงด้านล่างนี้มีประโยชน์กับคุณ ไม่ใช่ปัญหาจากการตอบสนอง แต่มาจากฟังก์ชันลูกศร
การอ้างอิงนี้เป็นการเขียนเกี่ยวกับปัญหานั้นอย่างชัดเจนมากขึ้น
ข้อมูลอ้างอิง
- Javascript ไวยากรณ์เก่าเพื่อแปลงฟังก์ชันลูกศร