使用AJAX将PHP变量转换为JS变量

时间:2017-02-21 08:29:42

标签: php jquery html ajax

我正在尝试将PHP变量转换为JS变量,因此我可以在我正在制作的游戏中使用它。当我检查地图代码时,它只是undefined。提前致谢。仅供参考PHP。

<script>
    var mapCode;
    var used;
    var active;

    function downloadCode() {
        $.ajax({
            type: 'GET',
            url: 'getMapCode.php',
            data: {
                mapCode: $mapCode,
                used: $used,
                active: $active,
            },
            dataType: "text",
        }); 
    }
</script>
<?php
  ini_set('display_errors', 1); 
  error_reporting(E_ALL);
  $servername = "localhost";
  $username = "username";
  $password = "password";
  $dbname = "database";

  // Create connection
  $conn = mysqli_connect($servername, $username, $password);
  mysqli_select_db($conn, $dbname);

  // Check connection
  if (!$conn) 
  {
    die("Connection failed: " . mysqli_connect_error());
  }
  // echo "Connected successfully";

  $query = "SELECT mapCode FROM mapCodes";
  $result = mysqli_query($conn, $query);
  $mapCode = mysqli_fetch_row($result);

  $query1 = "SELECT used FROM mapCodes";
  $result1 = mysqli_query($conn, $query1);
  $used = mysqli_fetch_row($result1);

  $query2 = "SELECT active FROM mapCodes";
  $result2 = mysqli_query($conn, $query2);
  $active = mysqli_fetch_row($result2);

  mysqli_close($conn);  
?>

据我所知,PHP代码很可怕,但它确实有效,而且当整个工作正常时,我会“非常好”

4 个答案:

答案 0 :(得分:1)

如果文件扩展名为.php而不是.js,那么这应该有效

<script>
    function downloadCode() {
        $.ajax({
            type: 'GET',
            url: 'getMapCode.php',
            data: {
                mapCode: "<?php echo $mapCode; ?>",
                used: "<?php echo $used; ?>",
                active: "<?php echo $active; ?>",
            },
            dataType: "text",
        });
    }
</script>

如果你有.js文件,那么在将你的js包含在.php文件中之前声明javascript变量

<script>
    var mapCode = "<?php echo $mapCode; ?>";
    var used = "<?php echo $used; ?>";
    var active = "<?php echo $active; ?>";
</script>

然后在.js文件中,您将轻松获得

<script>
    function downloadCode() {
        $.ajax({
            type: 'GET',
            url: 'getMapCode.php',
            data: {
                mapCode: mapCode,
                used: used,
                active: active,
            },
            dataType: "text",
        });
    }
</script>

答案 1 :(得分:0)

你只需要使用&lt;?php echo $ mapCode;?&gt;而是$ mapCode。 .... php变量无法打开Php标签

答案 2 :(得分:0)

我当前的项目实际上处理了很多ajax调用, 这是我用来与服务器通信的简化版本:

// php
// needed functions
function JSONE(array $array)
{
    $json_str = json_encode( $array, JSON_NUMERIC_CHECK );
    if (json_last_error() == JSON_ERROR_NONE)
    {
        return $json_str;
    }
    throw new Exception(__FUNCTION__.': bad $array.');
}
function output_array_as_json(array $array)
{
    if (headers_sent()) throw new Exception(__FUNCTION__.': headers already sent.');
    header('Content-Type: application/json');
    print JSONE($array);
    exit();
}

// pack all data
$json_output = array(
    'mapCode'   => $mapCode,
    'used'      => $used,
    'active'    => $active
);

// output/exit
output_array_as_json( $json_output );


// javascript
function _fetch()
{
    return $.ajax({
        url: 'getMapCode.php', // url copied from yours
        type: 'POST',
        dataType: 'json',
        success: function(data, textStatus, req){
            console.log('server respond:', data);
            window.mydata = data;
        },
        error: function(req , textStatus, errorThrown){
            console.log("jqXHR["+textStatus+"]: "+errorThrown);
            console.log('jqXHR.data', req.responseText);
        }
    });
}

window.mydata = null;
_fetch();

我没有对此进行过测试,但请告诉我,我会为您解决此问题。

答案 3 :(得分:0)

我是如何得到你的,你需要从ajax请求得到结果,要做到这一点,你应该首先设置你的php输出你的结果,所以ajax可以得到像这样的php输出结果:

<?php
  ini_set('display_errors', 1); 
  error_reporting(E_ALL);
  $servername = "localhost";
  $username = "username";
  $password = "password";
  $dbname = "database";

  // Create connection
  $conn = mysqli_connect($servername, $username, $password);
  mysqli_select_db($conn, $dbname);

  // Check connection
  if (!$conn) 
  {
    die("Connection failed: " . mysqli_connect_error());
  }
  // echo "Connected successfully";

  $query = "SELECT mapCode FROM mapCodes";
  $result = mysqli_query($conn, $query);
  $mapCode = mysqli_fetch_row($result);

  $query1 = "SELECT used FROM mapCodes";
  $result1 = mysqli_query($conn, $query1);
  $used = mysqli_fetch_row($result1);

  $query2 = "SELECT active FROM mapCodes";
  $result2 = mysqli_query($conn, $query2);
  $active = mysqli_fetch_row($result2);

  mysqli_close($conn); 
  // Outputing results:
  echo json_encode(array('mapCode'=>$mapCode[0], 'used'=>$used[0], 'active'=>$active[0]));
?>

然后在ajax中,在ajax完成后使用success监听返回消息:

<script>
    var mapCode;
    var used;
    var active;

    function downloadCode() {
        $.ajax({
            type: 'GET',
            url: 'getMapCode.php',
            data: {
                /** Your data to send to server **/
            },
            dataType: "text",
            success: function(data) { /** Here is data returned by php echo **/
                var temp = $.parseJSON(data);
                mapCode = temp['mapCode'];
                used = temp['used'];
                active = temp['active'];
            }
        }); 
    }
</script>