如何通过Javascript调用我的PHP文件

时间:2012-08-13 17:07:22

标签: php javascript html

  

可能重复:
  [PHP/JavaScript]: Call PHP file through JavaScript code with argument

好的,所以我使用Javascript来验证我的HTML表单输入值,但我使用PHP将这些值写入数据库。 是否可以通过Javascript将表单发送到PHP文件?

这是我没有使用Javascript的方式,当您单击PHP文件的提交按钮时,它应该发送表单。 这是我的原始形式:

<form name="filler" method="post" action="display.php">
//form stuff
</form>

据我所知。虽然我无法看到任何应该发生错误的事情,但是当我需要用Javascript验证我的表单时,没有任何事情发生,它只是在我输入的内容时立即进入PHP。它还有什么问题?

<!DOCTYPE HTML>

<html>
<head>
<script type="text/javascript">
    function required1(n,s,u,e,d,p,cp,g)  
    {  
        if (n.value.length > 0 && s.value.length > 0 && u.value.length > 0 && e.value.length > 0 && d.value.length > 0 && p.value.length > 0 && cp.value.length > 0 && g.value.length > 0)  
                {  
            return true;
        {
        else   
        {  
            alert('You have not filled in all the fields');  
            return false;   
        }  
    }
    function required2(e)
    {
        if(e.indexOf('.') != -1 && e.indexOf('@') != -1)
        {
            return true;
        }
        else
        {
            alert('Not a valid email address');
            return false;
        }   
    }
    function required3(d)
    {
        if(/^\d{2}\/\d{2}\/\d{4}$/.test(d))
        {
            return true;
        }
        else
        {
            alert('Date is not in the right format (DD/MM/YYY)');
            return false;
        }
    }  
</script>
</head>
<body>
<form name="filler" method="post" action="display.php" onsubmit="return required1(document.filler.name,document.filler.surname,document.filler.username,document.filler.email,document.filler.dob,document.filler.password,document.filler.confirm_password,document.filler.gender) && required2(document.filler.email) && required3(document.filler.dob) ">
    <input name="name" placeholder="Name..."/>
    <input name="surname" placeholder="Surname..."/>
    <input name="username" placeholder="Username..."/>
    <input name="email" placeholder="Email address..."/>
    <input name="dob" placeholder="YYYY/MM/DD"/>
    <input name="password" placeholder="Password" type="password"/>
    <input name="confirm_password" placeholder="Password" type="password"/>
    <input name="gender" placeholder="Gender..."/>
    <input type="submit" value="Submit"/>
</form>
</body>
</html>

7 个答案:

答案 0 :(得分:2)

没有理由为此使用AJAX。最优雅,最简单的方法是使用HTML表单标记的onsubmit事件:

<form name="filler" method="post" action="display.php" onsubmit="return validateForm()">
    //form stuff
</form>

这将在提交表单之前调用JS函数validateForm。如果函数validateForm返回false,则不会提交表单。否则它会像往常一样提交给你的PHP文件。

修改

确保您也在PHP中验证此输入,因为可以轻松禁用Javascript。

答案 1 :(得分:1)

正如在其他答案中所建议的那样,您可以向表单添加事件侦听器并在“客户端”(即使用javascript)进行验证。在提交之前,将调用此javascript函数 - 从函数中您可以停止提交表单(如果存在某些问题)。

另外,如上所述,重要的是不要依赖客户端验证。用户很容易禁用javascript,并且人们有这么多合理的理由;不要把它视为只有“无所不能”的人所做的事情。

但是,我不同意这里介绍的方法。 “内联javascript”,如在HTML标记中的javscript,通常被认为是不好的做法。在某些狭隘的情况下,它可能更合适,通常你最好从javascript附加事件

那就是说,这是一个如何做的例子:

<form id="my_form" name="filler" method="post" action="display.php">
//form stuff
</form>

..请注意我在您的表单中添加了id属性...

var validate_form = function (evnt) {
    var frm = evnt.target;
    var error = false;

    // validate here, if there is problem set error = true
    alert('validating fields');


    if (error != false) {
        evnt.preventDefault();  // stop the form from submitting
        // show an error message
        return;
    }        
};
window.onload = function () {
    var frm = document.getElementById('my_form');
    addEvent('submit', frm, validate_form);
};
// quickie cross-browser addEvent
var addEvent = function(event, target, method) {
    if (target.addEventListener) {
        target.addEventListener(event, method, false);
    } else if (target.attachEvent) {
        target.attachEvent("on" + event, method);
    }
}

为什么这样更好?

这种方法对内联javascript有几个好处。最重要的是,内联javascript只允许每个元素一个事件。如果您决定稍后要在表单中添加其他功能或功能,该怎么办?你要么必须将功能破解到你的validate_form功能(坏),要么你必须改为使用这种方法(浪费时间不要在第一时间做)!

其次,如果你决定稍后使用像jQuery这样的框架,那么更新这段代码的速度非常快(仅在你需要的时候...... )。您可能会更改window.onload,并且可以删除addEvent功能。

原始问题怎么样?

您最初的问题是从javascript调用PHP函数。正如所建议的那样,AJAX是实现这一目标的方法。我将向您展示一个“vanilla”示例(不需要库),并使用流行库(如jQuery)链接到一些示例。

首先,香草,请记住,这是非常基本的,但这可能就是你所需要的:

function ajax(url, callback) {
    var aj;
    if (window.XMLHttpRequest) {
        aj=new XMLHttpRequest();
    } else {
        // remove this else if you don't care about IE6 (I DON'T!)
        aj=new ActiveXObject("Microsoft.XMLHTTP");
    }
    aj.onreadystatechange=function() {
        if (aj.readyState==4 && aj.status==200) {
            callback(aj.responseText);
        }
    }
    aj.open("GET",url,true);
    aj.send();
    return aj;
}

要使用它,请致电ajax('http://myserver.org/myfile.php?value=1&anothervalue=2", callback_function);myfile.php中,您可以使用发布的数据,然后输出响应(说“1”表示一切正常,否则就是错误列表)。< / p>

jQuery用于ajax请求:

$.ajax({
  url: "http://myserver.org/myfile.php",
  context: document.body
}).done(function(response) { 
    // do something with the response
});

请参阅文档:http://api.jquery.com/jQuery.ajax/

...或mootools

  var req = new Request({
    url: 'http://myserver.org/myfile.php',
    onSuccess: function(txt){
        // do something with the result
    },
  });

请参阅演示:http://mootools.net/demos/?demo=Request

答案 2 :(得分:0)

例如,如果您的表单名称为“myform”,则提交调用的JavaScript代码为:

document.forms["myform"].submit();

答案 3 :(得分:0)

这是你想要的AJAX。

这个Bassistance jQuery validation plugin将是开始的。 Here是一些演示。

答案 4 :(得分:0)

如果没有看到html的其余内容,是的,无论javascript验证如何,您的表单都可能会被提交。

避免这种情况的最简单方法是在表单中添加onSubmit处理程序:

<form name="filler" method="post" action="display.php" onSubmit="return my_validate_function();">

现在,如果my_validate_function()返回false,您的表单将无法提交。

答案 5 :(得分:0)

按原样将它写在html文件中。

<?php
if ($ID = '') {
echo "<script language=javascript>alert('enter a valid username.')</script>";
}
?>

答案 6 :(得分:-1)

你应该使用JQuery或类似的东西。 查看http://api.jquery.com/jQuery.ajax/http://api.jquery.com/serialize/