使用AJAX将PHP变量发送到javascript

问题描述:

我有两个PHP变量,我想使用AJAX传递给javascript.

I have two PHP variables that I want to pass to javascript using AJAX.

test.php

$Longitude = json_encode($Long);
$Latitude =  json_encode($Lat);

Index.js

$.ajax({
  type: 'POST',
  dataType: "json",
  url:'test.php',
  data:
  success: function(data)
  {
    console.log("testing");
  }
});

我是编程新手.请指导如何在ajax调用中引用这些变量名称.

I am new to programming. Please guide how to refer these variable names in the ajax call.

传入数组并对其进行编码.

Pass in array and encode it.

test.php

$data = ['Longitude ' =>$Long, 'Latitude ' => $Lat ];

echo json_encode($data);

index.js

 $.ajax({
  type: 'POST',
  dataType: "json",
  url:'test.php',
  data:
  success: function(data)
  {
   try {
      data = JSON.parse(data);
    }catch(e) {}
    console.log(data);
  }
});