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.

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

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制