我有一个名为senttest.php的php文件。我想要做的是将一个变量从php发送到javascript,以便通过情绪分析工具运行它,然后将其发回到同一文件中的php。我可以把所有的东西都当作必要的工作,除了回复到php,当我回应它时,它会变空。我做错了什么想法或明显的想法?谢谢!
<?php
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
</head>
<body>
<?php
$full = 'Congratulations to our great military men and women for
representing the United States, and the world, so well in the Syria
attack.';
?>
<script type="text/javascript">var r1 = "<?= $full ?>";
var returntext = "";</script>
<script src="sentiment/bundle.js" type="text/javascript"></script>
<script type="text/javascript">
$.ajax({
url: 'senttest.php', //This is the current doc
type: "POST",
dataType:'json', // add json datatype to get json
data: ({returned: returntext}),
success: function(data){
console.log(data);
}
});
document.write(returntext);
document.write('done with send');
</script>
<?php
$jsongrab = $_POST['returned'];
$json = json_decode($jsongrab, true);
?>
<p><?php echo $jsongrab ?></p>
<p><?php echo $json['comparative']; ?></p>
</body>
</html>
答案 0 :(得分:0)
这不会像现在这样运作。 AJAX调用不适用于此,因为它不会显示提取的HTML。你想要的是一个带有post参数的重定向。 使用Rakesh Pai的片段:
function post(path, params, method) {
method = method || "post"; // Set method to post by default if not specified.
// The rest of this code assumes you are not using a library.
// It can be made less wordy if you use one.
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
for(var key in params) {
if(params.hasOwnProperty(key)) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
form.submit();
}
然后在设置returntext时调用post('senttest.php',{returned:returntext},'POST')
。