我已經嘗試了幾個小時來讓這個東西正常作業。我正在嘗試將 Title 的文本和 Content 的文本附加到 .json 檔案中。我在這里看到了很多類似的問題,但是使用 php 并且我不允許使用它(老師的規則)。
我嘗試了 Fetch API,但我發現它只處理來自 json 檔案的獲取請求。然而我只在這里找到了 ajax 函式,它們在它們前面使用 $ 。
我只是不知道如何在不使用 php 的情況下包含 json 檔案的位置。名稱檔案 = posts.json。json里面的例子: 圖片json
這是我的代碼 JS:
let form = document.getElementById('frm');
form.addEventListener('submit', PostBlog)
function PostBlog(){
let title = document.getElementById("txtTitle");
let content = document.getElementById("txtContent");
let data = {title1: title.value}
//let url = new URL("http://localhost:8080/admin.html");
//let parms = new URLSearchParams({title1: title.value, content1: content.value});
fetch("http://localhost:8080/admin.html",
{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data),
}
).then(receive).then(response => response.text()).then(Succeed).catch(problem)
}
function receive(response) {
if(!(response.ok)){
throw new Error("Didn't Receive " response.status);
}
return response;
}
function problem(error){
alert("Not Found " error);
}
function Succeed(data){
alert("Found " data);
}
HTML 重要部分:
<form id="frm">
<div class="form-group">
<label for="txtTitle">Title</label>
<input type="text" class="form-control" id="txtTitle">
</div>
<div class="form-group">
<label for="txtContent">Content</label>
<textarea class="form-control" id="txtContent" rows="3"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-primary">Reset</button>
</div>
</form>
最后是現場圖片
現場圖片
uj5u.com熱心網友回復:
Ajax 是一個術語,意思是“從 JavaScript 發出 HTTP 請求,在瀏覽器中運行,無需離開頁面”。
您不能使用它直接寫入服務器上的資料,因為不允許瀏覽器簡單地寫入服務器。如果這是可能的,那么谷歌主頁將每秒被破壞 30 次。
您需要一個服務器端行程來接受 HTTP 請求并將資料寫入檔案(盡管資料庫通常是更好的選擇,因為它可以解決同時寫入等問題)。如果您不想使用 PHP,那么您可以使用服務器支持的任何其他服務器端編程語言。如果您不想使用其中任何一種,則可以將服務器更改為支持您要使用的語言的服務器。
我嘗試了 Fetch API,但我發現它只處理來自 json 檔案的獲取請求。
Fetch API 可用于發出或多或少的任何型別的請求,帶有任何型別的有效負載和任何型別的回應。
然而我只在這里找到了 ajax 函式,它們在它們前面使用 $ 。
瀏覽器有兩個用于發出 Ajax 請求的 API。XMLHttpRequest 和 Fetch。(獲取更新)。
有許多第三方庫包裝了 XMLHttpRequest 和/或 Fetch 以提供替代 API。$是 jQuery 通常分配給的變數。它的主要 Ajax 輔助函式可以在ajax屬性中找到。
使用第三方庫并不能解決瀏覽器無法寫入服務器的問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/449420.html
標籤:javascript html json 阿贾克斯 获取 API
上一篇:如何使用AJAX獲取模型物件?
下一篇:如何從資料庫中獲取實際影像
