繁体   English   中英

我的Ajax请求返回成功但脚本没有执行?

[英]My Ajax request returns successful but the script isn't executed?

所以在post_action.php中我有一堆div被回应来测试我是否在我的ajax请求期间到达该文件。 当我点击.deletePost时,我收到一条警告,上面写着'已成功删除',这让我相信ajax请求正在运行,但是来自post_action.php的内容为“hello world”的div并不存在。 有什么想法吗?

post_action.php

<?php

include 'db_connect.php';
include 'functions.php';
sec_session_start();
echo "<div>Hello World</div>";
echo "<div>Hello World</div>";
echo "<div>Hello World</div>";
echo "<div>Hello World</div>";
if($_GET['action'] == "deletePost")
        deletePost($_GET['postTitle']);
function deletePost($title){
    $sql = "DELETE FROM blog WHERE Title = '$title'";
    mysqli_query($mysqli, $sql);
}
?>

的functions.php

<?php
function sec_session_start() {
    $session_name = 'sec_session_id'; // Set a custom session name
    $secure = false; // Set to true if using https.
    $httponly = true; // This stops javascript being able to access the session id. 

    ini_set('session.use_only_cookies', 1); // Forces sessions to only use cookies. 
    $cookieParams = session_get_cookie_params(); // Gets current cookies params.
    session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"], $cookieParams["domain"], $secure, $httponly); 
    session_name($session_name); // Sets the session name to the one set above.
    session_start(); // Start the php session
    session_regenerate_id(); // regenerated the session, delete the old one.  
}
?>

dbconnect.php

<?php
$host="localhost"; // Host name
$username="root"; // username
$password="********"; // password
$dbname="nightowl"; // Database name
$tblname="blog"; // Table name
$mysqli=mysqli_connect($host,$username,$password,$dbname);
mysql_connect("$host", "$username", "$password");
mysql_select_db("$dbname");
?>

使用Javascript

$(document).ready(function(){
$('.deletePost').click(function(){
    $.ajax({
        url:"scripts/post_action.php",
        data: {action: "deletePost",  postTitle: $(this).siblings("h3.blog").text()},
        success: function(){
            alert('DELETED SUCCESSFULLY');
        }
    });
});
});

对于在php post_actions.php脚本中回显的div,您需要执行以下操作:

success: function(response){
        $("#containerWhereDivsCome").html(response);
        alert('DELETED SUCCESSFULLY');
    }

在HTML中你必须首先准备一个元素(在这种情况下是div ):

<div id='container'>
</div>

然后你的成功ajax:

success: function(response){ //retrieves the return from php
        $("#container").html(response); //put the return inside the element that has id = container
        alert('DELETED SUCCESSFULLY');
    }

所以,你的:

echo "<div>Hello World</div>";
echo "<div>Hello World</div>";
echo "<div>Hello World</div>";
echo "<div>Hello World</div>";

将出现在id container的div内。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM