从表单操作调用JS函数,然后从JS调用PHP


call js function from form action then call php from js

我们可以直接从html中的表单操作调用php:

<form name='x' action = "filename.php">

在这种情况下,PHP 将以这种形式接收所有输入,即使我们不传递它们。

我们可以从 html 中的表单操作调用 js 函数吗?

<form name='x' action = "javascript:jsFunction();">

那么,从 js 函数调用 php?

jsFunction()
{   var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() 
    {
        if (xhttp.readyState == 4 && xhttp.status == 200) {
                document.getElementById("result").innerHTML = xhttp.responseText;}
    };
    xhttp.open("POST", filename.php, true);
    xhttp.send();
}

提示我无法使用 onsubmit,因为它将我从平台注销。换句话说,它从登录页面的开头重新加载平台。我正在研究集成,我对该平台没有明确的想法。

编辑 1:

现在,在 HTML 文件中:

<form enctype='multipart/form-data' id = "myform">
<input type='submit' value='Basic search' onclick = "i2b2.BLAST.jsFunction();">

JS文件:

i2b2.BLAST.jsFunction = function () 
{
   var myForm = document.getElementById('myForm');
    myForm.addEventListener('submit', function(event)
    {
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() 
    {
        if (xhttp.readyState == 4 && xhttp.status == 200)
        {
            document.getElementById("result").innerHTML = xhttp.responseText;
        }
     };
     xhttp.open("POST", blastresult.php, true);
     xhttp.send();
    event.preventDefault();
}); 
}

它从登录页面的开头重新加载平台!

编辑2:

我放了一些警报,看看按钮是否调用javascript。

i2b2.BLAST.jsFunction = function () 
{
   alert('hi');
    this.yuiTabs = new YAHOO.widget.TabView("BLAST-TABS", {activeIndex:1});//this two lines navigate to second tab
    this.yuiTabs.set('activeIndex', 1);
alert('hi');
    myForm.addEventListener('submit', function()
    {
       alert('hi');
        preventDefault();

该按钮调用js并显示第一个"hi",然后导航到第二个选项卡,然后重新加载页面。它停在第二个"嗨"。

任何帮助都非常感谢。谢谢。

是的,你可以,首先给你的表格一个ID

<form id="myForm"></form>

然后在 JavaScript 中尝试这个:

var myForm = document.getElementById('myForm');
myForm.addEventListener('submit', function(e)
{
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() 
    {
        if (xhttp.readyState == 4 && xhttp.status == 200)
        {
            document.getElementById("result").innerHTML = xhttp.responseText;
        }
     };
     xhttp.open("POST", filename.php, true);
     xhttp.send();
    e.preventDefault();
}); 

而不是:

<form name='x' action = "javascript:jsFunction();">

用:

<form name='x' onsubmit="jsFunction();">

您可以通过 AJAX 发布,如代码所示:

function jsFunction(event) {
    // prevent default event from taking place (submitting form to file)
    event.preventDefault();
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() 
    {
        if (xhttp.readyState == 4 && xhttp.status == 200) {
                document.getElementById("result").innerHTML = xhttp.responseText;}
    };
    xhttp.open("POST", filename.php, true);
    xhttp.send();
}

虽然你需要序列化你的数据并将其传递给xhttp.send(),但它需要被形式URL编码,如:key1=value1&key2=value2。你最好按照@mmm建议的方式使用 jQuery。