[英]Running JavaScript (and calling jQuery plugins) returned via AJAX call
[英]Running Javascript scripts sent via AJAX call
我對ajax及其功能了解不多。 我想通過ajax調用從另一個PHP頁面調用一個php頁面,但是它不起作用。 我只是希望在按“ index.php”中的刪除按鈕時顯示在“ delete.php”中的警報。
dbconnect.php
<?php
$conn = new mysqli($host, $user, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
config.php
<?php
$host="192.168.20.171";
$user="production";
$password="******";
$database="*****";
?>
index.php
<html>
<?php
include 'config.php';
include 'dbconnect.php';
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<table border="1">
<tr>
<th>categoryId</th>
<th>category</th>
<th>Operations</th>
</tr>
<?php
$sql_query = "select category_id,category from cscart_category_descriptions;";
$result = $conn->query($sql_query);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo '<tr><td>'.$row["category_id"].'</td><td>'.$row["category"].'</td><td><button class="deletedata" data-id="'.$row['category_id'].'">Del</button></td></tr>';
}
}
else {
echo "0 results";
}
?>
<script>
$(document).on('click','.deletedata',function(){
id = $(this).attr('data-id'); // Get the clicked id for deletion
$.ajax({
type:'GET',
url:'delete.php',
data:{delete_id:id},
success:function(response){
if (response == 'ok') {
alert("succes");
} else {
alert("fail");
}
}
})});
</script>
</table>
</html>
delete.php
<?php
include 'config.php';
include 'dbconnect.php';
if($_GET('delete_id'))
{
echo"<script>alert('jjjj');</script>";
}
?>
您在delete.php
文件中回顯的是作為Ajax response
返回的內容。
所以在這段代碼中:
$.ajax({
type:'GET',
url:'delete.php',
data:{delete_id:id},
success:function(response){
if (response == 'ok') {
alert("succes");
} else {
alert("fail");
}
}
})});
響應為<script>alert('jjjj');</script>
,這使您的代碼進入else並警告fail
。
你需要做的是回聲ok
在delete.php
然后警報jjjj
成功。 那將是:
//delete.php
include 'config.php';
include 'dbconnect.php';
if($_GET('delete_id'))
{
echo "ok";
}
您的ajax調用將是相似的,唯一不同的是您對成功發出警報的內容。
$.ajax({
type:'GET',
url:'delete.php',
data:{delete_id:id},
success:function(response){
if (response == 'ok') {
alert("jjjj");
} else {
alert("fail");
}
}
})});
通常,當您執行ajax調用並獲得響應時,您的下一個操作將取決於接收到的響應,因此,大多數情況下,您會遇到諸如alert(response)
(或任何利用從服務器接收到的信息的其他操作)之類的東西,而不是進行靜態警報。
在開始使用AJAX之前,您應該考慮學習更多有關AJAX的知識。
當您有一個delete.php
的GET
請求時,您可以將該script
從該php delete.php
到當前腳本中,但必須將其追加:
success:function(response){
// here response is the script tag from delete.php
$(document.head).append(response);
}
//delete.php
<?php
include 'config.php';
include 'dbconnect.php';
echo 'ok';
?>
無論您在php頁面中回顯什么,都會在ajax響應中回復您。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.