今天遇到一个奇怪的问题。因此,我尝试使用 AJAX 将数据插入数据库,这样页面就不需要重新加载来查看更改。但是当我尝试插入数据时,不知道如何放置它,insert.php 文件没有被“触发”,例如“Hello Im insert.php”行没有显示。但是ajax代码工作正常,成功 block 被触发。
表格:
<form action="insert.php" method="post" class="form-inline" id="forma">
<input type="text" class="form-control" name="inputName" id="inputName" placeholder="Name">
<input type="text" class="form-control" name="inputPrice" id="inputPrice" placeholder="Price">
<input type="text" class="form-control" name="inputStore" id="inputStore" placeholder="Store">
<input type="text" class="form-control" name="inputDate" id="inputDate" placeholder="Date"></br>
<button id="submit" type="submit" class="btn btn-success">Submit</button>
</form>
jQuery:
$('#forma').submit(function() {
var name = $("#inputName").val();
var price = $("#inputPrice").val();
var store= $("#inputStore").val();
var date = $("#inputDate").val();
$.ajax({
type: "POST",
url: "insert.php",
data: {
inputPavadinimas: name,
inputKaina: price,
inputParduotuve: store,
inputData: date,
},
success: function() {
$("#success").show();
alert('success');
},
error: function(){
alert('error');
}
});
return false;
});
插入.php:
<?php
error_reporting(0);
require 'db/connection.php';
echo 'Hello Im insert.php';
if(!empty($_POST)){
print_r($_POST);
if(isset($_POST['inputName'],$_POST['inputPrice'],$_POST['inputStore'],$_POST['inputDate'])){
$name = trim($_POST['inputName']);
$price = trim($_POST['inputPrice']);
$store = trim($_POST['inputStore']);
$date = trim($_POST['inputDate']);
if(!empty($name) && !empty($price) && !empty($store) && !empty($date)){
$insert = $db->prepare("INSERT INTO prekes(name, price, store, date) VALUES (?, ?, ?, ?)");
$insert->bind_param('ssss',$name, $price, $store, $date);
if($insert->execute()){
echo 'INSERTED';
}
}
}
};
最佳答案
要更改 PHP 脚本 echo 中的数据,您需要像这样更改成功函数。
success: function(data) {
$("#success").show();
alert(data);
},
success Type: Function( Anything data, String textStatus, jqXHR jqXHR ) A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter or the dataFilter callback function, if specified; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the success setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event.
在这里您可以找到有关jQuery.ajax()的更多信息
关于PHP 文件未使用 jQuery/AJAX 触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31093546/