javascript 如何在不刷新/重新加载页面的情况下在提交按钮上运行 php 代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13559489/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 19:09:16  来源:igfitidea点击:

how to run php code on submit button without refreshing/ reloading the page

phpjavascriptajaxsubmitpage-refresh

提问by Bkay

I want to execute some php code on submit button click without refreshing/reloading my page. Is it possible? also i have javascript function on page load that's why i don't want to refresh my page. thanks in advance.

我想在提交按钮点击时执行一些 php 代码而不刷新/重新加载我的页面。是否可以?我也有页面加载的 javascript 函数,这就是为什么我不想刷新我的页面。提前致谢。

<?php
if(isset($_POST["search"]))
{
$show = "SELECT * FROM data";
$rs = mysql_query($show) or die(mysql_error());
 $add_to_textbox = "<input type='button' name='btn' value='add' />";
#****results in Grid****
    echo "<table width='360px' border='1' cellpadding='2'>";
    $rowID=1;
while($row = mysql_fetch_array($rs))
{
    echo "<tr>";
    echo "<td width='130px' id='name.$rowID.'>$row[Name]</td>";
    echo "<td width='230px' id='link.$rowID.'><a href = '$row[Link]'>$row[Link]</a></td>";
    echo "<td width='130px' onclick='Display($rowID);'>$add_to_textbox</td>";
    echo "</tr>";
    $rowID++;
}
    echo "</table>";
#**********************
mysql_free_result($rs);
}
?>

<script type="text/javascript">
function Display(rowID){
    var linkVal = document.getElementById('link'+rowID+'').innerHTML.replace(/<\/?[^>]+(>|$)/g, "\n");
    document.getElementById("name").value = document.getElementById('name'+rowID+'').innerHTML;
    document.getElementById("link").value = linkVal; 
    }
</script>

here is my code

这是我的代码

回答by Andrew

Well, you need to use the javascript / ajax.

那么,你需要使用javascript/ajax。

Example: on your submit link (a href for exaple), add call-in-to js function submitMeand pass on whatever variables you need

示例:在您的提交链接(例如,a href)上,添加调用 js 函数submitMe并传递您需要的任何变量

function submitMe() {
    jQuery(function($) {    
        $.ajax( {           
            url : "some_php_page.php?action=getsession",
            type : "GET",
            success : function(data) {
                alert ("works!"); //or use data string to show something else
                }
            });
        });
    }

IF you want to change some content dynamically, it is easy- you just need to create tags, and assign ID to them : <div id="Dynamic"> </div>

如果您想动态更改某些内容,这很容易 - 您只需要创建标签,并为它们分配 ID: <div id="Dynamic"> </div>

Then you load ANYTHING between those two tags using

然后你加载这两个标签之间的任何东西

document.getElementById("Dynamic").innerHTML = "<b>BOOM!</b>";

Meaning that you calling area between two tags and loading something into them. The same way you GET data from that place:

这意味着您在两个标签之间调用区域并将某些内容加载到其中。与从该位置获取数据的方式相同:

alert(document.getElementById("Dynamic").innerHTML);

Please read this: http://www.tizag.com/javascriptT/javascript-getelementbyid.php

请阅读:http: //www.tizag.com/javascriptT/javascript-getelementbyid.php

In addition, play and experiment with DOM elements and learn how they interact. It is not hard, just takes some time to grasp all concepts.

此外,玩和试验 DOM 元素并了解它们如何交互。这并不难,只是需要一些时间来掌握所有概念。

回答by Louis Loudog Trottier

Whenever you send request ajax (with plain js anyway) from a html form, make sure you add the return false statement to prevent redirection: something like:

每当您从 html 表单发送请求 ajax(无论如何都使用纯 js)时,请确保添加 return false 语句以防止重定向:类似于:

<form method="post" ... onsubmit="ajax_post(); return false;">

You have to use ajax, but you can do it in plain javascript (without jquery). Jquery makes it easier.

您必须使用 ajax,但您可以使用纯 javascript(不使用 jquery)来完成。Jquery 使它更容易。

plain javascript example: This function will trigger an ajax, via get, without parameter: you can tweak it so it run in POST and be able to send some parameter: filerepresent the php file to request and htmlrepresent the container whre the data will be displayed:

简单的 javascript 示例:此函数将通过 get 触发 ajax,不带参数:您可以调整它,使其在 POST 中运行并能够发送一些参数:file表示要请求的 php 文件,html表示数据将要发送的容器显示:

function plain_ajax(file,html){
    if (window.XMLHttpRequest){ 
          r=new XMLHttpRequest();   //For Most BRowser
    } else{ 
          r=new ActiveXObject("Microsoft.XMLHTTP");  //for Explorer
    }

    //When the state change
    r.onreadystatechange=function(){ 
       //ReadyState 4 = Loaded     see: http://www.w3.org/TR/2006/WD-XMLHttpRequest-20060405/
       //status 200 = ok           see: http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
       if(r.readyState==4 && r.status==200){
           //Replace the content with the response, Using creatDocumentFragment is more efficient 
           //at the cost of a few more lines But it  would alos allow you to append the data
           //instead of replacing it using innerHTML;
           document.getElementById(html).innerHTML = r.responseText;
        }
    }

    //Opening the connection and sending the request.
    r.open("GET",file,true); 
    r.send();
}

回答by Pradeep

Your HTML or PHP form

您的 HTML 或 PHP 表单

<form action="submit.php"  method="post">
Name: <input name="name" id="name" type="text" /><br />
Email: <input name="email" id="email" type="text" /><br />
Phone Number: <input name="phone" id="phone" type="text" /><br />
<input type="button" id="searchForm" onclick="SubmitForm();" value="Send" />
</form>

Your JavaScript

你的 JavaScript

 <script>
 function SubmitForm() {
 var name = $("#name").val();
 var email = $("#email").val();
 var phone = $("#phone").val();
 $.post("submit.php", { name: name, email: email, phone: phone },
 function(data) {
 alert("Data Loaded: " + data);
 });
 }
 </script>

Your PHP page to do some activity

你的 PHP 页面做一些活动

 <?php
 echo $_POST['name']."<br />";
 echo $_POST['email']."<br />";
 echo $_POST['phone']."<br />";
 echo "All Data Submitted Sucessfully!"
 ?>