Ajax ResponseText为true,但无法写入div

时间:2019-06-17 15:27:14

标签: javascript php ajax wordpress

Ajax代码:

    jQuery(document).ready( function($) {
    var valueCheck;
    $('#acf-field_5cdc07b87c8f8-field_5cdc08405814f').on( 'change', function () {
         valueSelect = $(this).val();
         if ( parseInt ( valueSelect ) > 0 ) {
        $.ajax( ajaxurl, {
            type: 'POST',
            url: '<?php echo admin_url('admin-ajax.php'); ?>',
            data: { action: 'hesaplama', // The name of the WP action
                    value:  valueSelect,       // the dataVAlues
            },
            dataType: 'json',
            success: function ( response ) {     // to develop in case of success
                             if ( response.success ) {
                                  sonucum = response.html;  // Here we get the results of the PHP remote function
                                  $('#xcvb').html( sonucum );
                             }
                             else {
                                  $('#xcvb').html( '<span>Bu #id: ' +  valueSelect + ' ye ait bir içerik bulunamadı.</span>' );
                             }
                        },
            error: function ( errorThrown ) {   // to develop in case of error
                             console.log( errorThrown ); 
                        }, 
        });
         }
    });
});

Functions.PHP:

function hesaplayici(){
$id    = (int) $_POST['value'];
$sonucum =  the_field('sertifika_aciklamasi', $id);}

在控制台上显示响应文本,但无法写到我的div(id:#xcvb),有人可以帮我吗?

https://up.uac.ist/images/2019/06/17/Screenshot_2.png https://up.uac.ist/images/2019/06/17/Screenshot_3.png

2 个答案:

答案 0 :(得分:0)

请尝试这样:

在php端:

$return = ['myvarname' => 'your data here'];
echo json_encode($return);
exit(); 

在js方面:

success: function ( response ) { 
$(#idofyourdiv).html(response.myvarname);
}

答案 1 :(得分:0)

看起来您在这里有些错误。首先,我不确定您如何在其中运行带有PHP echo语句的jQuery。你不应该那样做。这是在Wordpress中使用Ajax的正确方法。

$.ajax({
            type: 'POST',
            url: ajax_object.ajax_url,
            data: {
                action: 'hesaplama',
                value: valueSelect
            }, 
            error: function (data) {
                console.log(data);
            }, 
            success: function (data) {

               console.log(data);
               if ( data == '') {
                  $('#xcvb').html( '<span>Bu #id: ' +  valueSelect + ' ye ait bir içerik bulunamadı.</span>' );
               }
               else {
                  $('#xcvb').append( data );
               }

            }
    });

您应该尝试回应您的回答。

function hesaplayici(){

$id = $_POST['value'];

$sonucum =  the_field('sertifika_aciklamasi', $id);

echo $sonucum;

die();

}

add_action( 'wp_ajax_send_hesaplayici', 'hesaplayici' );
add_action( 'wp_ajax_nopriv_hesaplayici', 'hesaplayici' );