为什么函数Javascript不执行?

时间:2022-06-09 02:29:21

I need to execute a function named "send()" who contain an ajax request. This function is in ajax.js (included in ) The Ajax success update the src of my image.

我需要执行一个包含ajax请求的名为“send()”的函数。这个函数在ajax.js中(包含在内)Ajax成功更新了我的图像的src。

This function work well, I don't think that it is the problem

这个功能运作良好,我不认为这是问题所在

But when I load the page, send() function is not executed :o I don't understand why.

但是当我加载页面时,send()函数没有被执行:o我不明白为什么。

After loading, I click on a button, and the function work ! (the code of the button is not in the code below)

加载后,我点击一个按钮,功能正常工作! (按钮的代码不在下面的代码中)

You can see the HTML code, my function below, and node JS code. Thanks for your help.

您可以看到HTML代码,我的函数和节点JS代码。谢谢你的帮助。

Since your answer, the problem is now : POST http://localhost:3000/index/gen/ net::ERR_CONNECTION_REFUSED

既然你的答案,现在的问题是:POST http:// localhost:3000 / index / gen / net :: ERR_CONNECTION_REFUSED

The script is executed, the problem was that some data were not initialized (Jquery sliders)

脚本执行,问题是一些数据没有初始化(Jquery滑块)

<!DOCTYPE html>

<html>
 <head>
    <meta charset="utf-8" />
    <title>Génération</title>
    <link rel="stylesheet" media="screen" title="super style" href="./styles/feuille.css">
    <script src="./script/ajax.js"></script>
    </head>
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>

    <body>
    <img src="images/map.jpg" class="superbg" alt="Carte du monde"/>

    <div id="main">
        <header>
            <div id="titre">  
                <h1>Generator</h1>
            </div>
        </header>                       

        <img id="image" src="" alt="Map">

        <script>
        send(); //in file ajax.js included in head
        alert($("#image").attr('src'));
        </script>

    <footer>
        Copyright CLEBS 2017, tous droits réservés.
    </footer>

    </body>
</html>

Here send function

这里发送功能

function send(){
        var data = {"some data useless for my question"};
        alert("i'm in send() function");
        $.ajax({
        type: 'POST',
        url: 'index/gen/', //(It's node JS)
        data: data,
        success : function(j){
            var img = document.getElementById('image');
            img.src = j;
        },
        complete : function(j){
            },
        });       
    }

Node JS code

节点JS代码

app.post('/index/gen/',urlencodedParser, function (req,res){                    
    const { spawn } = require('child_process');
    const ls = spawn('./generateur/minigen.py', 
    req.session.donnees = ''
    ls.stdout.on('data', (data) => {
        req.session.donnees+=data.toString();
    }); 
    ls.stderr.on('datas', (datas) => {
        console.log("Erreur"+`stderr: ${datas}`);
    });
    var options = {         //Encapsulation des données à envoyer
      mode: 'JSON',
      pythonOptions: ['-u'],
      scriptPath: './generateur',               //ligne du dessous c'est les valeurs saisies par l'utilisateur
      args: ["Some data useless for my question"]
    };
    pythonShell.run('generation.py', options, function (err, results) { //Make the map to be download 
        if (err) throw err;
        res.send(req.session.donnees);
    });
}
})

3 个解决方案

#1


0  

There is no function named send in your code. You have a function named envoi. Change function envoi() to function send() The hazards of multilingual coding!

您的代码中没有名为send的函数。你有一个名为envoi的函数。将函数envoi()更改为函数send()多语言编码的危险!

Edit: since you updated your answer, try this.

编辑:自从您更新了答案后,请尝试此操作。

<script>
$(document).ready(function() {
    send();
    alert($("#image").attr('src'));
});
</script>

#2


0  

You could use the onload Event. This Event is called, wenn the page is loded completely and you can reach the send() function.

你可以使用onload事件。调用此事件,如果页面完全被锁定,您可以访问send()函数。

https://www.w3schools.com/jsref/event_onload.asp

https://www.w3schools.com/jsref/event_onload.asp

https://www.w3schools.com/tags/ev_onload.asp

https://www.w3schools.com/tags/ev_onload.asp

For instance:

例如:

<body onload="myFunction()"> 

<script>
    function myFunction() {
        send(); //in file ajax.js included in head
        alert($("#image").attr('src'));
    }
</script>

#3


-1  

The format of the javascript is incorrect. The Scope of your solution needs to be managed with JQuery. If you simply want to call the function when the page loads, you can call the function inside the JQuery handler. Also, your syntax is not correct.

javascript的格式不正确。您的解决方案的范围需要使用JQuery进行管理。如果您只是想在页面加载时调用该函数,则可以在JQuery处理程序中调用该函数。此外,您的语法不正确。

<!DOCTYPE html>
<html>
 <head>
    <meta charset="utf-8" />
    <title>Génération</title>
    <link rel="stylesheet" media="screen" title="super style" href="./styles/feuille.css">


    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="./script/ajax.js"></script>
</head>
    <body>
    <img src="images/map.jpg" class="superbg" alt="Carte du monde"/>

    <div id="main">
        <header>
            <div id="titre">  
                <h1>Generator</h1>
            </div>
        </header>                       

        <img id="image" src="" alt="Map">

    <footer>
        Copyright CLEBS 2017, tous droits réservés.
    </footer>
     <script>
      $(function(){
         send(); //in file ajax.js included in head
         //  alert($("#image").attr('src')); <-- won't update inline due to async ajax
      })
     </script>
    </body>
</html>

Also, the image tag alert should be updated in the Async callback.

此外,应在Async回调中更新图像标记警报。

  var data = {"some data useless for my question"}
    $.ajax({
        url: 'index/gen/',
        type: "POST",
        data: JSON.stringify(data),
        contentType: "application/json",
        complete: function(j) {
         $("#image").attr('src', j);
        }
    });

Also be aware that you want JQuery to load before your custom JavaScript. I'm not sure where you are calling Envoi, but this code should help you. It will trigger the "send()" function when the page loads. Also, script tags should be included in the Head tag.

另请注意,您希望在自定义JavaScript之前加载JQuery。我不确定你在哪里打电话给Envoi,但这段代码可以帮助你。它会在页面加载时触发“send()”函数。此外,脚本标记应包含在Head标记中。

#1


0  

There is no function named send in your code. You have a function named envoi. Change function envoi() to function send() The hazards of multilingual coding!

您的代码中没有名为send的函数。你有一个名为envoi的函数。将函数envoi()更改为函数send()多语言编码的危险!

Edit: since you updated your answer, try this.

编辑:自从您更新了答案后,请尝试此操作。

<script>
$(document).ready(function() {
    send();
    alert($("#image").attr('src'));
});
</script>

#2


0  

You could use the onload Event. This Event is called, wenn the page is loded completely and you can reach the send() function.

你可以使用onload事件。调用此事件,如果页面完全被锁定,您可以访问send()函数。

https://www.w3schools.com/jsref/event_onload.asp

https://www.w3schools.com/jsref/event_onload.asp

https://www.w3schools.com/tags/ev_onload.asp

https://www.w3schools.com/tags/ev_onload.asp

For instance:

例如:

<body onload="myFunction()"> 

<script>
    function myFunction() {
        send(); //in file ajax.js included in head
        alert($("#image").attr('src'));
    }
</script>

#3


-1  

The format of the javascript is incorrect. The Scope of your solution needs to be managed with JQuery. If you simply want to call the function when the page loads, you can call the function inside the JQuery handler. Also, your syntax is not correct.

javascript的格式不正确。您的解决方案的范围需要使用JQuery进行管理。如果您只是想在页面加载时调用该函数,则可以在JQuery处理程序中调用该函数。此外,您的语法不正确。

<!DOCTYPE html>
<html>
 <head>
    <meta charset="utf-8" />
    <title>Génération</title>
    <link rel="stylesheet" media="screen" title="super style" href="./styles/feuille.css">


    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="./script/ajax.js"></script>
</head>
    <body>
    <img src="images/map.jpg" class="superbg" alt="Carte du monde"/>

    <div id="main">
        <header>
            <div id="titre">  
                <h1>Generator</h1>
            </div>
        </header>                       

        <img id="image" src="" alt="Map">

    <footer>
        Copyright CLEBS 2017, tous droits réservés.
    </footer>
     <script>
      $(function(){
         send(); //in file ajax.js included in head
         //  alert($("#image").attr('src')); <-- won't update inline due to async ajax
      })
     </script>
    </body>
</html>

Also, the image tag alert should be updated in the Async callback.

此外,应在Async回调中更新图像标记警报。

  var data = {"some data useless for my question"}
    $.ajax({
        url: 'index/gen/',
        type: "POST",
        data: JSON.stringify(data),
        contentType: "application/json",
        complete: function(j) {
         $("#image").attr('src', j);
        }
    });

Also be aware that you want JQuery to load before your custom JavaScript. I'm not sure where you are calling Envoi, but this code should help you. It will trigger the "send()" function when the page loads. Also, script tags should be included in the Head tag.

另请注意,您希望在自定义JavaScript之前加载JQuery。我不确定你在哪里打电话给Envoi,但这段代码可以帮助你。它会在页面加载时触发“send()”函数。此外,脚本标记应包含在Head标记中。