2013-04-06 82 views
0

我该如何去完成以下行为。发送javascript变量(来自knockout.js)到php并返回结果

  1. 在获得从knockout.js形式的输入发送可变的网页来处理。网页使用PHP

  2. PHP页面接收来自knockout.js形式输入,并运行一些计算,然后返回结果

  3. 的变量随后接收回原始页面上,然后经由显示淘汰赛

例如,假设我有以下

//knockout_form.js 
self.addItem = function() { 
    var itemNum = self.newItem; //variable received from knockout form 

    var returnedVariable = ???? **send itemNum to processing.php which will then return it** 

    self.itemNumbers.push(new ItemEntry(retunredVariable, "$20.00")); // 
} 

我知道的jQuery/AJAX可以为u sed发布到processing.php,但我如何将processing.php的计算数据返回到javascript页面?

下面编辑。数据似乎发送到了processing.php(显示在网络选项卡中),但警报未显示。

// Operations 
self.addItem = function() { 
    var itemNum = self.newItem; 

    $.getJSON("processing.php?itemNum=" + itemNum),function(data) { 
     alert(data); //this does not appear 
     self.itemNumbers.push(new ItemEntry(data.result, "$20.00")); 
    } 
} 

这里的PHP

​​
+0

检入jQuery的AJAX功能。 – 2013-04-06 22:37:38

+0

Knock out可以通过AJAX处理JSON数据:http://knockoutjs.com/documentation/json-data.html – Sukima 2013-04-06 22:40:01

回答

2

淘汰赛没有做Ajax调用本身的任何特殊方式,通常你会使用jQuery。请参阅http://knockoutjs.com/documentation/json-data.html

因此,像:

self.addItem = function() { 
    var itemNum = self.newItem; 

    $.getJSON("processing.php?itemNum=" + itemNum,function(data) { 
     self.itemNumbers.push(new ItemEntry(data.result, "$20.00")); 
    }); 
} 

这假设你的PHP脚本输出有效的JSON。例如:

<?php 
$result = doCalculations($_GET['itemNum']); 
echo json_encode(array("result" => $result)); 
?> 

这是未经测试的,但您明白了。

+0

PHP在接收并处理后如何返回到JavaScript页面?我看到了JSON位,但它实际上在哪里发回它?它只是回声吗? – user1406951 2013-04-06 22:42:50

+0

呃,看到上面的“回声”声明?这是json_encode()的结果并将其吐出。这将是ajax回调的数据。 – jszobody 2013-04-06 22:43:52

+0

数据似乎发送到processing.php(我检查了网络和价值正在发送),但没有任何被返回。有什么建议么? – user1406951 2013-04-06 23:08:07