【问题标题】:jQuery ajax done always fails on Wordpress在 Wordpress 上完成的 jQuery ajax 总是失败
【发布时间】:2014-01-08 22:06:29
【问题描述】:

我有下面的脚本,它用 ajax 擦除 MySQL 数据库上的一行。当函数被触发时,该行会从数据库中删除,但我总是会收到“FAILED”的警报。

function deleteRow(data){
if(confirm("Are you sure that you wish to remove this entry?\nThis cannot be undone")){
    $.ajax({
            type: "POST",
            url: "/wp-content/themes/Rexmed/deleterow.php",
            data: {id: data},
            dataType: "json"
        }).done(function() {
            alert("Success");
        }).fail(function() {
            alert("FAILED");
        });
}
}

这是 deleterow.php

<?php
require('../../../wp-blog-header.php');
if(!is_user_logged_in()){
auth_redirect();
die();
}

require ('../../../wp-config.php');
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$id = $_POST['id'];

if ($stmt = $mysqli->prepare("DELETE FROM customers WHERE id=?")) {
$stmt->bind_param("s", $id);
$stmt->execute();
$stmt->close();
}

【问题讨论】:

  • 完成/完成似乎很少被触发。我不完全确定它是依赖于浏览器还是浏览器之间的问题,但成功/错误往往是你最好的选择。
  • 调试:.fail(function(xhr, status, err) { console.log([xhr, status, err]); });
  • data: {id: data} 数据 = ?
  • php 脚本返回什么?使用 Firebug 或类似工具进行检查。
  • 你必须实际返回 JSON,你没有返回任何东西,所以它失败了

标签: javascript php jquery ajax wordpress


【解决方案1】:

更改 PHP 并返回 JSON

<?php
    require('../../../wp-blog-header.php');
    if(!is_user_logged_in()){
        auth_redirect();
        die();
    }

    require ('../../../wp-config.php');
    $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
    $id = $_POST['id'];

    if ($stmt = $mysqli->prepare("DELETE FROM customers WHERE id=?")) {
        $stmt->bind_param("s", $id);
        if ($stmt->execute()) {
            $arr = array('success' => 'true');
        }else{
            $arr = array('success' => 'false');
        }
        $stmt->close();
    }

    echo json_encode($arr);

?>

.done(function(data) {
     if (data.success == 'true') {
        alert('you did it');
     }
})

【讨论】:

  • 好的,我更改以反映您的修改,但我仍然“失败”。不知道为什么我在控制台上收到 404,因为该行已从数据库中删除。
猜你喜欢
  • 2015-04-07
  • 1970-01-01
  • 2013-01-04
  • 1970-01-01
  • 1970-01-01
  • 2019-06-08
  • 2010-10-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多