2

在我的index.php 文件中,我有一个 php 函数"InsertTheRecord",它获取一个参数并将其插入数据库。如果该参数插入成功,则返回 1,否则返回 0。

我在同一个 index.php 中有以下 JavaScript 函数"InsertRecord",我想从其中调用 php InsertTheRecord 函数。如何从 JavaScript 函数调用 php 函数?

我的 JavaScript 函数:

function InsertRecord() {
    var myParameter = 40;
    var result = ////call InsertTheRecord(myParameter) //I don't know how to do this?
    if result == 1 { //do something}
        else { //show error message}
}
4

5 回答 5

3

尝试

var result = <?php echo InsertTheRecord(myParameter); ?>


OP评论后更新

$.ajax

function InsertRecord() {
    $.ajax({
        type: "POST",
        url: "your_php_page.php",
        data: "arg1=id&arg2=name",
        success: function (data) {
            var myParameter = 40;
            var result = data;
            if result == 1 {} else {}
        }
    });
}
于 2013-11-09T10:39:27.923 回答
3

php 服务器端脚本语言和 javascript 是客户端脚本语言,你可以通过 ajax 调用(Jquery)来做到这一点

<div id="yourdiv"></div>

var data ="hello world";
var data2="hello all";
function run(){
$.ajax({ url: 'myscript.php',
         data: {'q': data,'z':data2},
         type: 'post',
         success: function(output) {
                     alert(output);
   document.getElementById("yourdiv").innerHTML += output; //add output to div  
            }
});
}

我的脚本.php

   <?php
myfun();

function myfun(){
$myvar2 = $_POST['z'];
$myvar = $_POST['q']."how are you?";
echo $myvar."\n";
echo $myvar2;
}
?>

这个警报“你好,你好吗?”

于 2013-11-09T10:42:24.373 回答
2

PHP 是服务器端,JS 是客户端,所以 PHP 先工作,然后 JS 在浏览器中动态工作。

您不能在运行时调用 PHP 函数。但是你可以使用 AJAX 来做到这一点。看看这个:http ://www.w3schools.com/ajax/ajax_aspphp.asp

于 2013-11-09T10:41:41.837 回答
0

这不可能

Javascript 是客户端脚本语言,而 PHP 是服务器端脚本语言 但是,您可以尝试 AJAX 方法来获得类似的结果,您可以传递与函数相同的变量

function myfunction(var1, var2 ,....){return var1*var2} 使用 ajax 一样,您可以在单击按钮时在外部运行 php 脚本 $.ajax({key:var},function(result){alert(result)});

http://www.w3schools.com/jquery/jquery_ajax_intro.asp

http://www.tutorialspoint.com/ajax/

于 2013-11-09T10:41:59.763 回答
0

如果您将 myParameter 回显到隐藏的输入字段,然后使用 javascript 抓取它会怎样:

HTML/PHP 文件:

<input type="hidden" id="myParameter" value="<?php echo InsertTheRecord(myParameter); ?>"/>

在 Javascript 中:

function InsertRecord() {
    var myParameter = 40;
    var result = document.getElementById("myParameter").value();
    if result == 1 { //do something}
    else { //show error message}
}
于 2013-11-09T10:45:47.760 回答