首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >为什么在WordPress中使用Ajax时,我会在控制台收到400 (错误请求)通知?

为什么在WordPress中使用Ajax时,我会在控制台收到400 (错误请求)通知?
EN

Stack Overflow用户
提问于 2019-03-01 03:43:16
回答 1查看 49关注 0票数 -1

注意,我进入了控制台:

发布http://localhost/mysite/wp-admin/admin-ajax.php

400 (错误请求)

Functions.php:注册JS文件并本地化脚本

代码语言:javascript
复制
function my_scripts_method() {



      wp_register_script('custom_script',
        get_stylesheet_directory_uri()  . '/js/jquery_test.js',
       array('jquery'),
       '1.0' );

      wp_enqueue_script('custom_script');


      wp_localize_script( 'custom_script', 'custom_script_object', array(
            'ajax_url' => admin_url( 'admin-ajax.php' )
        ));

            }
    add_action('wp_enqueue_scripts', 'my_scripts_method');

jquery_test.js文件:

代码语言:javascript
复制
var $j = jQuery.noConflict();

$j(function(){

    $j(".small-board-profile-member").click(function(){

  var fgfdgds =  $j(this).attr('value');
console.log(fgfdgds);


$j('.modal-body').attr('value', fgfdgds);

 $j.ajax({
    url : custom_script_object.ajax_url,
    type : 'post',
    data : {
        post_id : fgfdgds
    },
    processData: false,
    contentType: false,
    success : function( response ) {
        $j('.rml_contents').html(response);
        console.log("it worked");
    }
}); 



  });
});

我的php函数来处理ajax请求(放在functions.php中):

代码语言:javascript
复制
add_action( 'wp_ajax_my_action', 'my_action' );

function my_action() {
    global $wpdb; // this is how you get access to the database

    $whatever = ( $_POST['post_id'] );

    //$whatever += 10;

        echo $whatever;

    wp_die(); // this is required to terminate immediately and return a proper response
}

我认为问题出在处理ajax请求的php函数中。非常感谢您的宝贵时间!

EN

回答 1

Stack Overflow用户

发布于 2019-03-01 03:58:24

编辑:

在javascript中更改:

代码语言:javascript
复制
var $j = jQuery.noConflict();

$j(function () {

    $j(".wpb_wrapper").click(function () {

        var fgfdgds = $j(this).attr('value');

        var formData = new FormData();
        formData.append("post_id", 'fgfdgds');
        formData.append("action", 'my_action');


        $j('.modal-body').attr('value', fgfdgds);

        $j.ajax({
            url: custom_script_object.ajax_url,
            type: 'post',
            data: formData,
            processData: false,
            contentType: false,
            success: function (response) {
                $j('.rml_contents').html(response);
                console.log("it worked");
            }
        });



    });
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54933139

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档