我有一个文件search.php,我从表单中获取输入,然后创建一个url。我希望数据(url_api)将其传递给AJAX脚本,我可以在其中请求json。如何将变量api_url传递给ajax数据?
这是我的代码:
if(filter_input(INPUT_POST, 'submit')){
$area=filter_input(INPUT_POST, 'm', FILTER_SANITIZE_STRING);
// The access url is created with data from the form
$api_url = "http://wwww/api/v1/wwww?";
if ($m !== "") {
$api_url = $api_url . "m=" . $m;
}
$api_url = $api_url . "&api_key=wxaaaaaaaaaaaaaaaaaaaaaaaa";
和ajax脚本
$.ajax({
url: 'search.php', //This is the current doc
type: "POST",
dataType:'jsonp', // add json datatype to get json
data: ?,
success: function(data){
console.log(data);
}
});
答案 0 :(得分:1)
在你的JS脚本中:
$.ajax({
url: 'search.php', //target PHP script
type: 'POST', //data will be send with POST method
dataType: 'json', //data will be sent as JSON
data: { //data sent to PHP script
key1: 'val1', //keys / values
key2: 'val2'
},
success: function(data) {
//get the url sent back by PHP and do whatever you want with it
console.log(data.url);
}
});
在PHP脚本中:
//get data post by Ajax as POST parameters
$key1Val = $_POST['key1']; // === 'val1'
$key2Val = $_POST['key2']; // === 'val2'
//build your $url
//send back built URL to your JS script as JSON
echo json_encode([
'url' => $url
]);