簡體   English   中英

只需單擊一個按鈕即可調用php函數

[英]call a php function with a click of a button

你怎么用ajax或javascript或jquery調用php函數?

這是我的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調用連接的文件在服務器上可用。

所以假設你的函數在文件中:functions.inc.php

你可以有一個包含functions.inc.php的php文件,並調用submitmessage函數。

ajax_responder.php:

require_once 'functions.inc.php';    

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

現在,您可以使用ajax_responder.php的URL來提交消息。

使用jQuery包含或寫入頁面的形式:

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

然后,您不必提交表單,而是將提交按鈕更改為調用submitmessage javascript的按鈕:

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

作為旁注,為了安全起見,我建議您使用POST數據執行更多操作,以確保不會獲得SQL注入 由於您已經在使用mysql函數,因此可以嘗試使用mysql_real_escape_string

暫無
暫無

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

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