wp_send_json_error 返回带有请求失败标记的JSON数据给Ajax请求

Posted in:
Update time:2024-01-05

函数描述

发送 JSON 响应给一个Ajax请求,标记请求失败了。此响应总是有一个 success 键,值为 false,如果传递了其他数据到此函数中,传入的数据将被编码为 data 键的值。

Usage

wp_send_json_error( $data );
// 编码前数据看起来应该是这个样子的
$response = array( 'success' => false ); //如果 $data 为空
$response = array( 'success' => false, 'data' => $data ); //如果设置了 $data

function parameter

parametersdata typeRequired or notdescriptivedefault value
$datamulti-be需要格式化为JSON 的数据not have

usage example

jQuery(document).ready(function(){

    jQuery('#btn_save').click(function(e){
       e.preventDefault();
         jQuery.post(pluginUrl+'ajax/save_field.php',jQuery('#my-form').serialize(), function(data) {
              c-alert(data.success);                
         });
    });

});

save_field.php

$nonce=$_POST['_wpnonce_name'];
if (empty($_POST) || !wp_verify_nonce($nonce, 'my-nonce') ){
    wp_send_json_error(); // sends json_encoded success=false
}

related function

wp_send_json: 返回 json 格式的数据给客户端

wp_send_json_success: 返回带成功标记的 json 数据给客户端

We offer WordPress Themes and Plugins Custom Development Services

This site has long undertaken WordPress themes, plugins, WooCommerce-based store mall development business. We have 10 years of experience in WordPress development, if you want to Developing Websites with WordPress, please contact WeChat: iwillhappy1314 or email: amos@wpcio.com for inquiries.

发表回复

Your email address will not be published. 必填项已用 * 标注

*