在wordpress响应中请求ajax错误请求

时间:2020-08-26 09:20:45

标签: php jquery wordpress

我的Wordpress插件有问题:

$.ajax(send_rendered_photo.ajaxurl+"?action=save_photo",{
  type: "POST",
  data:{imgURL: dataURL},
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  complete: function(response){

  },
  success: function(data) {
      alert(data.data);
  },
  error: function(data){
      alert("fail");
  }
});
return false;
 

当我的js文件中包含此jQuery代码时,响应为 null ,而在PHP $_POST['imgURL']中,响应为 null ,但是当我具有以下条件时:

$.ajax(send_rendered_photo.ajaxurl,{
  type: "POST",
  data:{
        imgURL: dataURL,
        action: "save_photo",
        },
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  complete: function(response){

  },
  success: function(data) {
      alert(data.data);
  },
  error: function(data){
      alert("fail");
  }
});
return false;

在控制台中有:

POST http:// localhost:81 / wordpress / wp-admin / admin-ajax.php 400(错误 请求)

这是我的PHP:

function l_m_add_ajax_js(){
  wp_enqueue_script('l_m_ajax_render_photo', plugins_url('scripts/save_photo.js', __FILE__), true);
  if(isset($_SERVER['HTTPS'])){
    $protocol = 'https://';
  }
  else{
    $protocol = 'http://';
  }
  $params = array('ajaxurl'=>admin_url('admin-ajax.php',$protocol));
  wp_localize_script('l_m_ajax_render_photo','send_rendered_photo', $params);
}

add_action('wp_footer', 'l_m_add_ajax_js');
add_action('wp_ajax_save_photo', 'save_photo');
add_action('wp_ajax_nopriv_save_photo', 'save_photo');
function save_photo(){
  $imgURL = $_POST['imgURL'];
  $response = array(
    'success'=>true,
    'data'=>$imgURL
  );
  print json_encode($response);
    exit;
}      

我不知道问题出在哪里。谢谢您的帮助

编辑: 有标头和响应的照片send_rendered_photo.ajaxurl response

headers

这是完整的js代码

$("#save").on('click',function(){
                html2canvas(document.getElementById("create")).then(function (canvas) {
                var dataURL = canvas.toDataURL("image/png", 0.9);
                alert(dataURL);//dataURL is ok
               $.ajax(send_rendered_photo.ajaxurl+"?action=save_photo",{
                        type: "POST",
                        data: dataURL,
                        dataType: "json",
                        complete: function(response){

                        },
                        success: function(data) {
                            alert(data); // data is undefined
                        },
                        error: function(data){
                            alert("fail");
                        }
                    });
               return false;
           });
            });

编辑编辑: 我将js文件“ data:{imgURL:dataURL}”更改为“ data:dataURL”,将$ .ajax更改为$ .post并成功了

1 个答案:

答案 0 :(得分:0)

您确定您的 send_rendered_photo.ajaxurl 变量包含正确的URL并且不为空吗?