我尝试通过"jquery $.post“和"fwrite php”将数据放入js文件中,然后将数据返回到数组中。如何做到这一点?
下面是html:
<!doctype html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<script>
$(document).ready(function() {
$("#button").click(function() {
if ($("#nameput").val() != "") {
$.post("processing.php", {
putname: $("#nameput").val()
});
var arr = [$.getScript("talk.js")];
alert(arr[0]);
}
})
})
</script>
</head>
<body>
<input type="text" id="nameput" />
<button id="button">send AJAX req</button>
</body>
</html>下面是php,我将其命名为"processing.php“:
<?php
$file = fopen("talk.js","a");
$text = $_POST["putname"];
fwrite($file,'"'.$text.'",');
fclose($file);
?>"talk.js“看起来像这样:
"a","b","c",为什么我不能像上面html文件一样将"talk.js“中的数据放入”var arr = $.getScript("talk.js");“处的数组中?
以下是我在阅读评论后所做的尝试。我将scirpt更改为:
<script>
$(document).ready(function() {
$("#button").click(function() {
if ($("#nameput").val() != "") {
$.post("processing.php", {
putname: $("#nameput").val()
}, function() {
$.getScript("talk.js", function(data) {
var arr = data.split(",");
alert(arr[0]);
})
})
}
})
})
</script>并将php放入以下内容:
<?php
$file = fopen("talk.js","a");
$text = $_POST["putname"];
fwrite($file,$text);
fclose($file);
?>但是它还是不能工作?
发布于 2015-11-05 11:02:03
以下是按钮单击的简化版本,可帮助您解决问题:
$("#button").click(function() {
$.getScript("talk.js", function(data){
var arr = data.split(',');
alert(arr[0]);
});
});如果您记录$.getScript的输出,您将很容易看到为什么您正在尝试的东西不起作用。
使用这个方法,您将获得从脚本("a","b","c")返回的数据,但是您需要将它以逗号split到一个数组中。然后,您可以引用数组的任何部分。
请注意,数组的每个元素周围都有引号。
https://stackoverflow.com/questions/33535716
复制相似问题