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 asp.textbox后台赋值前端不能显示什么原因
  • ¥15 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误