我需要将字符串写入 notes.json 文件。我的 php 脚本由于某种原因无法正常工作。没有错误,只是该行没有添加到文件中。
应用程序:
import React, {
Component
} from "react";
import Notes from "./Notes.js";
import $ from "jquery";
import {
withoutIndex
} from "./utils.js"
class App extends Component {
constructor(props) {
super(props);
this.state = {
notes: []
};
}
componentDidMount(){
this.getNotes();
}
async getNotes(){
let notesList = [];
await $.getJSON('./api/notes.json', function(data) {
for(let i = 0; i<data.length; i++){
notesList.push(data[i].text);
}
});
await this.setState({
notes: notesList
});
}
async onNoteCreate(newNodeText){
this.setState(oldState => {
return {
notes: [newNodeText].concat(oldState.notes)
};
});
$.ajax({
url: './api/saveNote.php',
method: 'GET',
async: false,
data: {
text: newNodeText
}
});
}
render() {
return <Notes
notes={this.state.notes}
onDelete={this.onNoteDelete.bind(this)}
onCreate={this.onNoteCreate.bind(this)}
/>;
}
}
export default App;
保存笔记.php:
<?php
$text = $_POST["text"];
$notes = json_decode(file_get_contents("./api/notes.json"));
array_push($notes, ["text" => $text]);
file_put_contents("./api/notes.json", json_encode( $notes ));
notes.json 文件如下所示:
[{"text":"lorem ipsum dolor sit amet"},
{"text": "aezakmi"}]
单击按钮时,我需要将带有输入字段值的“文本”键添加到 notes.json 文件中。
作者可能已经找到答案了。在不检查其余代码的情况下,对于其他有类似问题的人,我想提请注意工作与交换方法的巧合。也许不是所有的代码。但从您所见,由于某种原因,方法进行了
get保存,并且读取了变量以保存方法post。在这种情况下,不仅没有什么可保存的,而且初始化变量时一定有错误。