从Javascript调用php函数,并在php代码中使用JavaScriptvar

Calling a php function from Javascript and using a javascript var in the php code

本文关键字:php JavaScriptvar 代码 Javascript 调用 函数 并在      更新时间:2023-09-26

JavaScript

function calcPrimesLoop() {
    var primes = document.getElementById('primes');
    primes.appendChild(document.createTextNode(''n'+this.prime.nextPrime()));
    $.ajax({
        url: "/test.php",
        type: "post",
        data: {prime: this.prime.nextPrime()},
        success: function(data) {
        } 
    });
    calcPrimesDelay = setTimeout('calcPrimesLoop()', this.delay);
}

Php

<?php
    $content = $_POST['prime'];
    $fn = "content.txt";

    $content = stripslashes('prime'"'n");
    $fp = fopen($fn,"a+") or die ("Error opening file in write mode!");
    fputs($fp,$content);

    fclose($fp) or die ("Error closing file!");

?>

所以我认为这就是所有相关的脚本。我有一个可以得到素数的脚本,它非常有效。但现在我想把这些数字记录在一个文本文件中。这就是我努力做到的,但我根本没有成功。非常感谢。问题是这些数字没有被记录下来。

我添加了一个Ajax正在工作的警报。但是,当我向php脚本添加一个表单并提交它时,它就起作用了。因此,ajax和php脚本本身并不能协同工作。

您应该了解AJAX,了解如何使用Javascript将信息传递到服务器端页面并检索返回值。

http://www.w3schools.com/ajax/default.asphttps://www.youtube.com/watch?v=qqRiDlm-SnY

使用ajax和jQuery,它实际上很简单。

function calcPrimesLoop() {
    var primes = document.getElementById('primes');
    primes.appendChild(document.createTextNode(''n'+this.prime.nextPrime()));
    $.ajax({
        url: "myScript.php",   // URL of your php script
        type: "post",
        data: {prime: this.prime.nextPrime()},
        success: function(data) {
            alert("success");
        } 
    });
    calcPrimesDelay = setTimeout('calcPrimesLoop()', this.delay);

}

myScript.php:

<?php
    $content = $_POST['prime'];
    ...

您应该明确查找异步JavaScript和XML。

您可以选择使用AJAX和Javascript函数,也可以使用jQuery简化您的生活

这是一个示例:

//STEP ONE: INCLUDE THE LAST VERSION OF JQUERY
<script src="http://code.jquery.com/jquery-latest.min.js"
    type="text/javascript"></script>
//STEP TWO, GET YOUR FUNCTION TO WORK:
function sendVariableTo(variable,url) {
    $.ajax({
        url:url, //Or whatever.php
        type: "GET", //OR POST
        data: { myVar: variable}, //On php page, get it like $_REQUEST['myVar'];
        success:function(result){
            //If the request was ok, then...
            alert(result) //Result variable is the php page 
            //output (If you echo "hello" this alert would give you hello..)
        },
    });
}

希望这有帮助,再见!