dongmi1221 2015-11-05 02:36
浏览 142

jquery $ .getScript()..如何将外部js文件中的数据导入数组

I try to put data into js file, through "jquery $.post" and "fwrite php", and get back that data into array. How to do that?

here's the 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
    $file = fopen("talk.js","a");
    $text = $_POST["putname"];
    fwrite($file,'"'.$text.'",');
    fclose($file);
?>

And "talk.js" will look like this :

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

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
    $file = fopen("talk.js","a");
    $text = $_POST["putname"];
    fwrite($file,$text);
    fclose($file);
?>

But it still not work?

  • 写回答

1条回答 默认 最新

  • douguanci9158 2015-11-05 03:02
    关注

    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.

    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. Then you can reference whichever part of the array you want.

    Note that the each element of the array will have quotations around them.

    评论

报告相同问题?

悬赏问题

  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?