我需要将一个数组变量传递给Ajax请求
<?
$postData = array(
'FirstName'=>$_POST['user_name'],
'Telephone'=>$_POST['user_phone'],
'Description' =>$_POST['komment'],
'Classifierid'=>'5E0696FD-831E-E611-9426-005056BAB261'
);
$postData = json_encode($postData);?>
我需要将$ postData传递给ajax变量数据:
$(document).ready(function () {
var postData=<?php $postData ?>;
$.ajax({
url: "http://XXXXXXXXX/api/CallBackForm",
type: "POST",
crossDomain: true,
data: I need to put $posData here,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
});
});
`
我成功获得$ postData。所有代码都在一个php页面中。
答案 0 :(得分:3)
定义$postData
,如:
<?php $postData = json_encode(array('FirstName'=>$_POST['user_name'])); ?>
您可以直接发送没有datatype
的Json,如:
$.ajax({
url: "http://XXXXXXXXX/api/CallBackForm",
type: "POST",
crossDomain: true,
data: '<?php echo $postData; ?>',
});
或者如果你必须使用dataType: 'json'
和ContentType选项(对服务器端很重要),你可以在发送ajax之前解析json:
$.ajax({
url: "http://XXXXXXXXX/api/CallBackForm",
type: "POST",
crossDomain: true,
data: JSON.parse('<?php echo $postData; ?>'),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
});