如果让我说我在一个php文件中,如何将回调javascript响应传递给php? 这是一个例如test.php的样本片段
<html>
<head>
<script>
var _somestuff = _somestuff || [];
(function () {
_somestuff.push(['id', blahblah], ['setApiKey', "blahblah"]
);
var d = document, g = d.createElement('script'), s = d.getElementsByTagName('script')[0];
g.type = 'text/javascript';
g.defer = true;
g.async = true;
g.src = 'blahblah.js';
s.parentNode.insertBefore(g, s);
})();
function myCallback(response)
{
if (response !== undefined) {
var data = JSON.parse(response);
var item_ids = data.items;
console.log(item_ids);
}
}
_somestuff.push(['blahblah',"001124","blahblah","myCallback"]);
</script>
</head>
<body>
</body>
</html>
我想要发生的是,使用php显示数据或html体内的item_ids ..怎么做?,我在一个页面,我不想使用ajax或其他什么,是那可能吗?
答案 0 :(得分:1)
如果PHP和你的JS在同一页面
exit;
放在PHP代码的最后一行伪:
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if(isset($_POST["someData"])) {
// Do some stuff with someData
// return /*anything you need*/; // this return will be collected by the AJAX success
}
}
exit; // Prevents the AJAX to return the whole document (with HTML etc)
?>
<html>
<head>
<script>
// JS AJAX POST someData TO PHP (use the same url)
// on success use the returned data by the PHP's `return`
</script>
</head>
<body>
</body>
</html>
答案 1 :(得分:0)
我通过将myCallback函数分配给像
这样的变量来解决了我的问题var a = function myCallback(response)
{
if (response !== undefined) {
var data = JSON.parse(response);
var item_ids = data.items;
console.log(item_ids);
}
};
然后将变量传递给
_somestuff.push(['blahblah',"001124","blahblah",a]);
然后在myCallback if条件中,我只是操纵了那里的html并加载了数据响应:)