【问题标题】:Ajax get request succeds on localhost but fails onlineAjax 获取请求在 localhost 上成功,但在线失败
【发布时间】:2019-06-30 08:11:10
【问题描述】:

我正在尝试通过 Wordpress 中的 ajax get 请求获取数据,我在 javascript 中编写了一个脚本,在 php 中编写了另一个脚本来处理它。

javascript的代码如下:

window.loadServices = function loadServices(){
var data = {
          action: 'get_services',
          perpage: '6',
        };
$.ajax({
 type: 'GET',
 url: sendbooking.ajaxurl,
 data: data,
 dataType: 'json',
 success: function (response) {
   post = response.data;
   console.log(response);
   $.each(post, function(){
     elem = $(this)[0];
     media = elem._links['wp:featuredmedia']
     var media_href;
     $.each(media, function(){
       media_href = $(this)[0].href;
     })
     // console.log(elem);

     var image;

     $.ajax({
       type: 'GET',
       url: media_href,
       dataType: 'JSON',
       success: function(data){
         image = data.source_url;
       },
       async: false,
     })

     $('.services .elements .elements-container').append(
      $('<div />', {
        class: 'loader',
      }).append(
        $('<img />', {
          src: '/wp-content/themes/farmhouse/assets/images/loader.gif'
        })
      )
     )

     setTimeout(function(){
       $('.loader').fadeOut();
     }, 2000);
     $('.services .elements .elements-container').append(
       $('<div />', {
         class: 'element '+elem.type,
       }).append(
           $('<a />', {
             href: elem.link
           }).append(
             $('<div />', {
               class: 'element-image',
             }).append(
               $('<img />', {
                 src: image,
               })
             )
           )
        ).append(
          $('<h5 />', {
            class: 'element-title',
          }).append(
            $('<a />', {
              href: elem.link,
              text: elem.title.rendered
            })
          )
        )
     )
     setTimeout(function(){
       $('.loader').remove();
     }, 2000);
   })
  },
 });
}

这是 php 的代码:

if(!function_exists('get_services')):
    function get_services(){

        $data = $_GET;
        $json_feed = get_site_url() . '/wp-json/wp/v2/service?per_page='.$data['perpage'];
       $json = file_get_contents($json_feed);
       $json_decoded = json_decode($json);

        wp_send_json_success($json_decoded);

 }

 add_action('wp_ajax_get_services', 'get_services');
 add_action('wp_ajax_nopriv_get_services', 'get_services');
endif;

我遇到的问题是在本地主机上,这工作正常,我得到了我需要的内容,没有任何问题。当我要在线部署站点时,ajax 不会检索任何内容。抛出console.logs,我注意到从api url(file_get_contents)获取数据时脚本失败,但如果你直接通过浏览器的地址栏或邮递员去那里,数据会正确提供。 (可以测试:http://www.dsoftwarelab.it/ilpiastrino/wp-json/wp/v2/service?per_page=6)。

我真的不知道如何解决它,因为我真的尝试了一切。

【问题讨论】:

    标签: json ajax wordpress rest api


    【解决方案1】:

    案例 1:您没有服务器的访问权限。

    如果您有 root 访问权限,请编辑 php.ini,通常位于 /etc/php.ini。

    如果您没有root权限,请尝试添加ini_set('allow_url_fopen', 'On');ini_set('allow_url_fopen', '1');.

    如果看不到 php.ini,请尝试在 PHP 脚本中使用 phpinfo() 来查找 php.ini 位置。

    案例 2:您错过了 .

    中的 SSL 参数
    $url= 'https://example.com';
    
    $arrContextOptions=array(
          "ssl"=>array(
                "verify_peer"=>false,
                "verify_peer_name"=>false,
            ),
        );  
    
    $response = file_get_contents($url, false, stream_context_create($arrContextOptions));
    

    案例 3:403 FORBIDDEN

    服务器以“403 FORBIDDEN”状态码响应。所以 file_get_contents() 工作正常,但是您尝试访问的服务器(或代理或介于两者之间的东西)不允许它。

    【讨论】:

    • 试图设置这些值,但它没有注册任何东西(在本地它确实如此)。没有启用 ssl。服务器在执行该操作时给出状态 200。
    • @LuigiBriganti 是您的文件内容响应吗?将数据转储到文件中。
    • 考古学家。
    • @Coder 你是什么意思?
    • @VasimShaikh 内容响应,在 localhost 中是一个包含我的数据的数组,但在线结果为“false”,就像服务器无法从提供的 url 读取任何数据一样。这是我不明白的吗?
    【解决方案2】:

    不要将 json 转换为数组。评论此行$json_decoded = json_decode($json);

    if(!function_exists('get_services')):
        function get_services(){
    
            $data = $_GET;
            $json_feed = get_site_url() . '/wp-json/wp/v2/service?per_page='.$data['perpage'];
            $json = file_get_contents($json_feed);  
    
            //dont need this line
            //$json_decoded = json_decode($json);
    
            wp_send_json_success($json);
    
        }
    
     add_action('wp_ajax_get_services', 'get_services');
     add_action('wp_ajax_nopriv_get_services', 'get_services');
    endif;
    

    【讨论】:

    • 如果我不在 php 中解码 json,那么我必须在 javascript 中使用 JSON.parse 进行解码,结果是一样的,因为我从 wp_send_json_success 得到的只是一个包含我的 json 的字符串,对我提供的js脚本没用(你检查过吗?)。
    • 你应该使用 jsonparse
    猜你喜欢
    • 1970-01-01
    • 2018-02-02
    • 1970-01-01
    • 1970-01-01
    • 2020-08-28
    • 1970-01-01
    • 1970-01-01
    • 2022-09-30
    • 1970-01-01
    相关资源
    最近更新 更多