Json API响应未附加在li属性

时间:2017-05-29 07:50:35

标签: jquery json api asp.net-ajax

我想使用ul和li来显示来自API的菜单,但是ajax响应不会附加在li中。请帮助我。

这是我的HtML

@{
    ViewData["Title"] = "Home Page";
}
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<div id="demo">
    <ul><li id="results"></li></ul>
</div>

这是我的剧本。

<script>
    $.ajax({
        url: "http://any-url",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        type: "POST",
        data: JSON.stringify({ "ProjectId": "1" }),
        success: function (response) {
            var title = +response.ParentList;
            console.log(response);
            $.each(response, function () {

                $("#results").append(title.Name);
            })

        },
        error: function (status)
        {
            console.log(status.statusText);

        }
    });
</script>

这是我控制台窗口中的Ajax响应。

Object {Message: "Successfully", Status: "OK", Parentlist: Array(10)}
Message:"Successfully"
Parentlist:Array(10)
0:Object
1:Object

Parentlist:Array(10)
 0:Object
  Child:Array(0)
  DisplayOrder:"-8"
  Id:"1012"
  Name:"Mysorie Chif

4 个答案:

答案 0 :(得分:1)

试试这个

 success: function (response) {
        $.each(response.ParentList, function () {
            $("#demo ul").append('<li>'+this.Name+'</li>');
        })
    },

答案 1 :(得分:0)

HTML:

@{
    ViewData["Title"] = "Home Page";
}
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<div id="demo">
    <ul><li class="results"></li></ul>
</div>

脚本:

<script>
    $.ajax({
        url: "http://any-url",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        type: "POST",
        data: JSON.stringify({ "ProjectId": "1" }),
        success: function (response) {
            var title = +response.ParentList;
            console.log(response);
            $.each(response, function () {

                $("#demo ul").append(title.Name);
            })

        },
        error: function (status)
        {
            console.log(status.statusText);

        }
    });
</script>

答案 2 :(得分:0)

我认为你的ajax调用正在返回一个数组(有关这方面的更多信息可能会受到欢迎)。

以下是如何迭代响应项并为每个项添加新的LI:

function onSuccess(response){
  $.each(response, function (index, item) {
    $("#resultRoot").append('<li>'+item.Name+'</li>');
  })
}

要使其工作,您需要指向UL标记(而不是LI):

<div id="demo">
    <ul id="resultRoot"></ul>
</div>

我按原样保留Ajax,只需调用onSuccess函数:

$.ajax({
    url: "http://any-url",
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    type: "POST",
    data: JSON.stringify({ "ProjectId": "1" }),
    success: onSuccess,
    error: function (status)
    {
        console.log(status.statusText);
    }
});

答案 3 :(得分:0)

我会使用这一行<?php namespace app\controllers; use Yii; use app\models\Users; use app\models\UsersSearch; use yii\web\Controller; use yii\web\NotFoundHttpException; use yii\filters\VerbFilter; /** * UsersController implements the CRUD actions for Users model. */ class UsersController extends Controller { /** * @inheritdoc */ public function behaviors() { return [ 'verbs' => [ 'class' => VerbFilter::className(), 'actions' => [ 'delete' => ['POST'], ], ], ]; } /** * Lists all Users models. * @return mixed */ public function actionIndex() { $searchModel = new UsersSearch(); $dataProvider = $searchModel->search(Yii::$app->request->queryParams); return $this->render('index', [ 'searchModel' => $searchModel, 'dataProvider' => $dataProvider, ]); } /** * Displays a single Users model. * @param integer $id * @return mixed */ public function actionView($id) { return $this->render('view', [ 'model' => $this->findModel($id), ]); } /** * Creates a new Users model. * If creation is successful, the browser will be redirected to the 'view' page. * @return mixed */ public function actionCreate() { $model = new Users(); if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $model->id]); } else { return $this->render('create', [ 'model' => $model, ]); } } /** * Updates an existing Users model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id * @return mixed */ public function actionUpdate($id) { $model = $this->findModel($id); if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $model->id]); } else { return $this->render('update', [ 'model' => $model, ]); } } /** * Deletes an existing Users model. * If deletion is successful, the browser will be redirected to the 'index' page. * @param integer $id * @return mixed */ public function actionDelete($id) { $this->findModel($id)->delete(); return $this->redirect(['index']); } /** * Finds the Users model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * @param integer $id * @return Users the loaded model * @throws NotFoundHttpException if the model cannot be found */ protected function findModel($id) { if (($model = Users::findOne($id)) !== null) { return $model; } else { throw new NotFoundHttpException('The requested page does not exist.'); } } }

这将<?php use yii\helpers\Html; use kartik\grid\GridView; use yii\widgets\ActiveForm; use yii\widgets\Pjax; use yii\web\JsExpression; /* @var $this yii\web\View */ /* @var $searchModel app\models\SalesOrderSearch */ /* @var $dataProvider yii\data\ActiveDataProvider */ ?> <div class="start-stock-index"> <div class="form-group"> <?= Html::a('Create Customer', ['create'], ['class' => 'btn btn-success']) ?> </div> <?php Pjax::begin(); ?> <?= GridView::widget([ 'dataProvider'=>$dataProvider, 'filterModel'=>$searchModel, 'showPageSummary'=>true, 'pjax'=>true, 'striped'=>true, 'hover'=>true, 'responsiveWrap' => false, 'panel'=>['type'=>'primary', 'heading'=>$partner_name], 'columns'=>[ [ 'attribute' => 'cust_name', 'value' => 'cust_name', 'label' => 'Name', 'contentOptions' => ['style'=>'max-width: 100px; font-size: 12px;overflow: auto; word-wrap: break-word;'], ], [ 'attribute' => 'phone_number', 'value' => 'phone_number', 'label' => 'Phone Number', 'contentOptions' => ['style'=>'max-width: 100px; font-size: 12px;overflow: auto; word-wrap: break-word;'], ], [ 'attribute' => 'age_type', 'value' => 'ageType.age_name', 'label' => 'Age Category', 'contentOptions' => ['style'=>'max-width: 100px; font-size: 12px;overflow: auto; word-wrap: break-word;'], ], ['class' => 'kartik\grid\ActionColumn','template' => '{update} {delete}',], ], ]); ?> <?php Pjax::end(); ?> </div> <?php $script = <<< JS JS; $this->registerJs($script); ?> 一个$("#demo ul").append('<li>' + this.ParentList.Name + '</li>');,并且使用append您应该获得当前li的名称值

this.ParentList.name