dop82210 2018-10-23 22:49
浏览 60
已采纳

var从php文件到带有ajax的js文件

In my main.php file in the main root i'm using:

$isWebView = false;
    if((strpos($_SERVER['HTTP_USER_AGENT'], 'Mobile/') !== false) && (strpos($_SERVER['HTTP_USER_AGENT'], 'Safari/') == false)) :
    $isWebView = true;
    elseif(isset($_SERVER['HTTP_X_REQUESTED_WITH'])) :
    $isWebView = true;
    endif;

echo json_encode($isWebView);

to check if is webview or browser and i save result as a boolean in the $isWebView var.

now i'm trying to load that result in my main.js file inside scripts folder like below but it doesn't work, why? i get error data is not defined.

$.ajax({
    url: 'main.php',
    type: 'POST',
    dataType: 'json',
    data: data,
    success: function(data){
        console.log(data);
    }
  });
  • 写回答

1条回答 默认 最新

  • douyou4819 2018-10-23 23:50
    关注

    Define the value of data inside the ajax request call

    $.ajax({
        url: 'main.php',
        type: 'POST',
        dataType: 'json',
        data: {},
        success: function(result){
            try{
              JSON.parse(result);
              console.log(result.isWebView)
            } catch (err) {
              console.log("non json respone");
            }
        }
      });
    

    Inside the php

    $response = [];
    
    $response['isWebView'] = false;
    
    if ( (strpos($_SERVER['HTTP_USER_AGENT'], 'Mobile/') !== false) && (strpos($_SERVER['HTTP_USER_AGENT'], 'Safari/') == false) ) {
        $response['isWebView'] = true;
    } elseif( isset($_SERVER['HTTP_X_REQUESTED_WITH']) ) {
        $response['isWebView'] = true;
    }
    
    echo json_encode($response);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应