只需单击一个按钮即可调用php函数 [英] call a php function with a click of a button

查看:68
本文介绍了只需单击一个按钮即可调用php函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用ajax或javascript或jquery调用php函数?

how do you call a php function with ajax or javascript or jquery?

这是我的php脚本

function submitmessage() {
    $sent = date(y-m-d-h-m-s);
    $message = $_POST['message'];
    $query = "INSERT INTO chatbox (from,to,message,sent)                            
    VALUES('$fullname','$to','$message','$sent')";
    mysql_query($query) or die(mysql_error());
}


推荐答案

拥有AJAX的文件呼叫连接在服务器上可用。

Have the file that the AJAX call connects to be available on the server.

所以假设你的功能在文件中:functions.inc.php

So lets say your function is in the file: functions.inc.php

你可以有一个包含functions.inc.php的php文件并调用submitmessage函数。

You could have a php file that includes the functions.inc.php and calls the submitmessage function.

ajax_responder.php:


ajax_responder.php:

require_once 'functions.inc.php';    

if(!empty($_POST)) {
    submitmessage();
}

现在您可以使用ajax_responder.php的URL来提交消息。

Now you can use the URL to the ajax_responder.php to submit messages.

将jQuery包含或写入页面,格式为:

With jQuery included or written into the page with form:

function submitmessage(){
    $.post("url_path/ajax_responder.php", { fullname: document.chatbox.fullname.value, message: document.chatbox.message.value } );
}

然后,您不必提交表单,而是将提交按钮更改为按钮调用submitmessage javascript:

Then, instead of submitting a form, you change your submit button into a button that calls the submitmessage javascript:

<button onclick="submitmessage()">Submit Message</button>

作为附注,为了安全起见,我建议您使用POST数据做更多事情以确保你没有得到 SQL注入。由于您已经在使用mysql函数,可以尝试 mysql_real_escape_string

As a side note, for security, I recommend that you do something more with the POST data to ensure that you do not get SQL injection. Since you are already using mysql functions you could try mysql_real_escape_string.

这篇关于只需单击一个按钮即可调用php函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆