2013-04-06 22:32


How can I go about accomplishing the following behavior.

  1. upon getting an input from a knockout.js form send the variable to a page to be handled. The page uses PHP

  2. The PHP page receives the input from the knockout.js form and runs some calculations and then returns the result

  3. The variable is then received back on the original page and is then displayed via knockout

For example, say I have the following

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")); //

I know that jQuery/Ajax can be used to post to processing.php, but how do I return the calculated data from processing.php back to the javascript page?

edit below. The data appears to be sent to processing.php (shows up in the network tab) but the alert isn't showing.

// 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"));

Here's the php

//$result = $_GET['itemNum'];
$result = "test";  //set it just to be sure it's working
echo json_encode(array("result" => $result));
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • duanhongxian6982 duanhongxian6982 8年前

    Knockout doesn't have any special way of doing ajax calls itself, typically you would use jQuery. See http://knockoutjs.com/documentation/json-data.html.

    So something like:

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

    This assume that your PHP script is outputting valid JSON. Something like:

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

    This is untested, but you get the idea.

    点赞 评论 复制链接分享