duanpanbo9476 2013-04-06 22:32
浏览 68
已采纳

发送javascript变量(从knockout.js)到php并返回结果

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

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

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));
  • 写回答

1条回答 默认 最新

  • duanhongxian6982 2013-04-06 22:40
    关注

    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:

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

    This is untested, but you get the idea.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥15 绘制多分类任务的roc曲线时只画出了一类的roc,其它的auc显示为nan
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?