簡體   English   中英

如何將數據從JavaScript發布到php,然后再返回到同一JavaScript函數

[英]How to POST data to php from JavaScript and then back into that same JavaScript Function

例如:

file.js

function math() {
    var one = 1;
    var two = 2;
    var equals = mathFunc(one,two); /*go to mathFunc and that's where the issue is*/
    var four = equals+one;
    document.write(equals);
}

mathFunc(x,y) {
    var one = x;
    var two = y;
    $.POST('file.php', {one: x,two: y});
}

file.php

<?php
$one = $_POST["one"];
$two = $_POST["two"];
$three = $one + $two;
?>

這是我要執行的操作,但不添加1 + 2。 除此之外,還需要以這種方式發生。

我可以做

var answer = $.POST('file.php', {one: x,two: y});
return answer;

編輯:我正在使用的數據對於GET方法太敏感

嘗試獲得結果為

$.POST('file.php', {one: x,two: y},function(result){
    return result;
});

甚至如你所說

var result = $.POST('file.php', {one: x,two: y});
return result;

而在你file.php嘗試echo的結果作為

$one = $_POST["one"];
$two = $_POST["two"];
$three = $one + $two;
echo $three;exit;

您需要在file.php中打印任何內容以獲取o / p。

但是您不是在打印,而是在計算。 所以你沒有得到o / p。

嘗試

echo $three;  

在file.php中

而且mathFunc()不返回任何值,因此您不會得到o / p。

所以返回這樣的值

var three = $.POST('file.php', {one: x,two: y});;
return three;
function math() {
    var one = 1;
    var two = 2;
    mathFunc(one,two); /* go to mathFunc and that's where the issue is */

}
function showResult(result,one){
   var four = eval(result+one);  // or sum(result,one);
   document.write(four);
}

mathFunc(x,y) {
    var one = x;
    var two = y;
    $.post('file.php', {one: x,two: y},function(result){
    showResult(result,one);
    });

你應該這樣

暫無
暫無

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

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