Dies ist das erste Mal, dass ich HTML PHP und Ajax verwende, also haben Sie bitte etwas Geduld. Der gr??te Teil des Codes stammt aus Beispielen, die ich online gefunden habe. Ich kann es jedoch nicht tats?chlich in die Datenbank einfügen. Die Ajax-Funktion geht in die Erfolgsfunktion ein; die Erfolgsausgabe wird lediglich als Warnung in der PHP-Datei angezeigt.
Ich habe das alles lokal, also starte ich Chrome als
chrome --allow-file-access-from-files file:///C:/filepath/index2.html
Ich wei?, dass es nicht gut ist, aber ich komme zurecht.
index.html
<html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <title>Insert</title> </head> <body> <label>Name</label> <input type="text" id="name"> <label>Email</label> <input type="text" id="email"> <button type="submit" id="button">SAVE</button> <script> $(document).ready(function(){ $("#button").click(function(){ var name=$("#name").val(); var email=$("#email").val(); $.ajax({ url:'insert.php', method:'POST', data:{ name:name, email:email }, success:function(data){ alert(data); }, error:function(data){ alert(JSON.stringify(data)); } }); }); }); </script> </body> </html>
.php einfügen
<?php $name=$_POST['name']; $email=$_POST['email']; $conn = new mysqli('Azure server URL', 'Username','Password', 'tableName'); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql="INSERT INTO data ('id', 'name', 'email') VALUES (NULL, $name, $email)"; if ($conn->query($sql) === TRUE) { echo "data inserted"; } else { echo "failed"; } ?>
你說(shuō)
...這不僅不好,而且是造成問(wèn)題的原因。 Chrome + 您的文件系統(tǒng)無(wú)法執(zhí)行 PHP 代碼。
您需要使用具有可用 PHP 運(yùn)行時(shí)的適當(dāng) Web 服務(wù)器,以便它支持執(zhí)行 PHP 來(lái)響應(yīng) HTTP 請(qǐng)求。使用 XAMPP 或 Laragon 安裝功能齊全的 PHP 開(kāi)發(fā)環(huán)境,其中 PHP、Apache 和 MySQL/MariaDB 可用且已配置,因此您可以在本地計(jì)算機(jī)上正確開(kāi)發(fā)和測(cè)試。
快速修復(fù)的另一個(gè)選項(xiàng)是 PHP 內(nèi)置網(wǎng)絡(luò)服務(wù)器 一旦你安裝了 PHP 就可以使用,雖然它的功能比較有限,但它與真實(shí)的部署環(huán)境不太相似,顯然如果你也需要數(shù)據(jù)庫(kù)等組件,你需要設(shè)置你自己?jiǎn)为?dú)說(shuō)一下。