簡體   English   中英

通過html按鈕調用javascript函數

[英]call a javascript function through html button

我有一個簡單的問題,已被問過很多次,但我無法解決。 我只是想從 html 組件部分,調用一個 javascript 文件來運行一個命令,點擊一個按鈕。

但是當我點擊按鈕時什么也沒有發生。

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">

</head>
<body>

<p id="counter">Loading button click data.</p>


<button  id="buttonForScraping">begin to scrape!</button>
<script>
  function startScrape(){
    jQuery.ajax({
      type:'get',
      url:'../../../scraping.js',
      data:[],
      dataType:'json',
      success: function(rs)
      {},
      failure : function(rs)
      {}
    });
  }
</script>
</body>

</html>

This is the html code, and the js file is : 


const {exec}  = require('child_process');
const button = window.document.getElementById('buttonForScraping');
button.addEventListener('click', function(e) {

exec('scrapy crawl address', (err, stdout, stderr) => {


  console.log(`stdout: ${stdout}`);
  console.log(`stderr: ${stderr}`);

});});

scrapy 命令是一個 python 命令,所以我需要調用 ajax 來在服務器上運行它,我想。

謝謝你的幫助!

要在服務器端運行代碼,您實際上需要一個服務器來響應請求。 看起來像這樣:

const { exec }  = require('child_process');
const app = require("express")(); // "npm install express" to install this dependency

app.get("/adress", (req, res) => { // server this path
 exec('scrapy crawl address', (err, stdout, stderr) => {

   res.json({ // respond to client if the command was done
     stdout: "" + stdout,
     stderr: "" + stderr
   });

});

app.listen(80,() => console.log("server started"));

如果您使用node ./scrapping.js啟動腳本,這將在端口 80 上打開一個服務器,如果您在http://localhost/ node ./scrapping.js訪問它,則使用 JSON 進行響應

現在,無論何時在前端單擊按鈕,您都必須向后端啟動一個 aJAX 請求:

// "async" lets us write callbacks more gracefully
button.addEventListener('click', async function(e) {
 try {
  // fetch is like $.ajax, but its native
  // 'await' is like a callback
  const { stdout, stderr } = await fetch("http://localhost/adress").then(res => res.json());
   console.log(stdout, stderr);
 } catch(err) {
   console.error("error occured while pinging server", err);
 }
});

要在單擊按鈕時執行 JavaScript 函數,您可以使用這樣的示例

首先,創建 HTML 按鈕並使用 onClick():

<button onClick="doSomething()">Button Text</button>

onClick() 告訴瀏覽器執行 JavaScript 函數。 現在在 JavaScript 文件中創建你的函數:

function doSomething() {
  alert('do something');
  console.log('do something ')
}

這個簡單的函數輸出到控制台日志並引發警報,但函數可能會變得比這復雜得多。

要從 HTML 頁面執行服務器端方法或 python 命令,您可能需要更復雜的架構。

您必須像示例中一樣將 js 文件包含到 html 文件中。 注意:確保script src屬性中 js 文件的路徑正確。 <script src ="myScript.js"></script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM