簡體   English   中英

從Ajax結果為ng-init賦值

[英]Assigning value to ng-init from Ajax result

我有一個帶有一個輸入字段的表單,用於通過AJAX提交student id ,並且正在從AJAX請求中獲取一些JSON結果。 現在,需要在表格下方的輸入字段( phone )中將AJAX請求返回的數據分配給ng-init 請幫助我如何將此值分配給ng-init 謝謝!

的HTML

<div ng-app="">
    <form id="std_form">
        <input type="text" name="sid" id="sid">
        <input type="submit">
    </form>

    <input type="text" name="phone" ng-model="phone" ng-init="" id="phone">
    Ph: {{phone}}
</div>

jQuery的

$('#std_form').submit(function(e){
    e.preventDefault();
    var val = $('#sid').val();
    var dataString = "sid=" + val;
    $.ajax({
        type: "POST",
        url: "post_process.php",
        data: dataString,
        dataType: 'json',
        success: function(data){
            $('#phone').val(data.phone);
        }
    });
});

post_process.php

<?php

if(ISSET($_POST['sid'])) {

    $sid = $con->real_escape_string($_POST['sid']);

    $sql = "SELECT phone FROM std_detials WHERE sid = $sid";
    $result = $con->query($sql);
    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $phone = $row['phone'];
    }
    $json = array('phone' => $phone);
    $json = json_encode($json);
    echo $json;
}

?>

您沒有將ng-model用於學生ID字段。 在成角度時按角度說做。 該代碼混合了傳統的PHP提交技術,然后通過Jquery進行了ajax調用。 嘗試盡可能消除這種做法,並適當地崇拜框架。

試試這個代碼。 了解並申請。 簡要:
我使用了Angular的$http post調用而不是jquery的$.ajax 您可以保持相同的通話或使用本機角度的通話。

刪除了一些不必要的標記。在輸入學生ID時添加了ng-model,在用於提交的按鈕上添加了ng-click功能,並對代碼進行了一些結構化。 如果您有用於項目的單獨的services.js文件,請在此處添加服務代碼,或者像我在此處的代碼中所做的那樣僅添加新服務。

因此,基本上您不需要ng-init來解決此問題。 應該在極少數情況下使用。 請在這里閱讀文檔。 https://docs.angularjs.org/api/ng/directive/ngInit

希望能幫助到你 ! 如有任何疑問,請告訴我。

<div ng-app="myApp">
  <form id="std_form">
    <input type="text" ng-model="sid">
    <button ng-click="submitSid()"></button>
  </form>

  <input type="text" ng-model="phone">
  Ph: {{phone}}
</div>

JS

var app = angular.module('myApp', []);
app.controller('MyCtrl', ['StudentService', function(StudentService){
   $scope.submitSid = function(){
    var data = {sid: $scope.sid};
    StudentService.getStudentDetails(data).then(function(res){
        console.log(res);
        $scope.phone = res.phone; // Or change to res.paramName. Just check in console to confirm the res logged.
    })
}
}]);

 app.factory('StudentService', ['$http', '$httpParamSerializerJQLike',           function($http, $httpParamSerializerJQLike){

  var getStudentDetails = function(data){
  var params = $httpParamSerializerJQLike(data);
    return $http({
        method: "POST",
        url: "post_process.php",
        headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'},
        data: params
    }).then(function(response){
      return response.data;
    });
}

return {
    getStudentDetails : getStudentDetails
}   
}]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM