简体   繁体   English

jQuery $ .getScript()..如何从外部js文件获取数据到数组

[英]jquery $.getScript().. How to get data from external js file into array

I try to put data into js file, through "jquery $.post" and "fwrite php", and get back that data into array. 我尝试通过“ jquery $ .post”和“ fwrite php”将数据放入js文件,然后将这些数据取回数组。 How to do that? 怎么做?

here's the html: 这是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>

Here's the php, I name it "processing.php" : 这是php,我将其命名为“ processing.php”:

<?php
    $file = fopen("talk.js","a");
    $text = $_POST["putname"];
    fwrite($file,'"'.$text.'",');
    fclose($file);
?>

And "talk.js" will look like this : 而且“ talk.js”将如下所示:

"a","b","c",

Why I can't put that data from "talk.js" into array at " var arr = [$.getScript("talk.js")]; " as in html file above? 为什么我不能将“ talk.js”中的数据放入“ var arr = [$ .getScript(“ talk.js”)] ;;”中的数组中,如上面的html文件中所示?

Here's what I try after I read comments. 这是我阅读评论后尝试的方法。 I change the scirpt into this: 我将脚本更改为:

<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>

And php into this: 和PHP成这样:

<?php
    $file = fopen("talk.js","a");
    $text = $_POST["putname"];
    fwrite($file,$text);
    fclose($file);
?>

But it still not work? 但这仍然行不通吗?

here's a simplified version of your button click to help you out: 这是您单击按钮的简化版本,以帮助您:

$("#button").click(function() {
    $.getScript("talk.js", function(data){
        var arr = data.split(',');
        alert(arr[0]);
    });
});

If you log the output of $.getScript you will easily see why what you're trying doesn't work. 如果您记录$.getScript的输出,您将很容易理解为什么您尝试的内容不起作用。

Using this method you will get the data returned from the script ( "a","b","c" ), but you'll need to split it on a comma into an array. 使用此方法,您将获得脚本( "a","b","c" )返回的数据,但需要split其以逗号split为数组。 Then you can reference whichever part of the array you want. 然后,您可以引用所需数组的任何部分。

Note that the each element of the array will have quotations around them. 请注意,数组的每个元素周围都会带有引号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM