wp_send_json 返回JSON格式的数据给Ajax请求

Posted in:
Update time:2024-01-05

函数描述

发送一个 JSON 相应到 AJAX 请求, 然后 die().

Usage

<?php wp_send_json( $response ) ?>

function parameter

parametersdata typeRequired or notdescriptivedefault value
$responsemulti-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.message + " ID:" + data.ID);
         });
    });

});

save_field.php

<?php
//引入 WP
$nonce=$_POST['_wpnonce_name'];
if (empty($_POST) || !wp_verify_nonce($nonce, 'my-nonce') ) die('Security check');

$return = array(
	'message'	=> 'Saved',
	'ID'		=> 1
);

wp_send_json($return);

related function

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

wp_send_json_error: 返回带错误标记的 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. 必填项已用 * 标注

*