未解析时json未定义,解析时出现意外令牌

时间:2017-10-04 07:34:22

标签: javascript php json postgresql

在javascript中从SQL查询中获取json响应时遇到问题

这是我的javascript

  setNouvelle: function(id, action){
        this
    .$http
    .get('news.api.php?function=getNouvelle&id='+id)
    .then(function(response){
      if (action == 'modal') {
        this.modal.nouvelle = response.data;
      } else if(action == 'edit') {
        this.nouvelle = response.data;
        this.nouvelle.publication = 
        moment(this.nouvelle.publication).format('YYYY-MM-DD');
      }
    });
},

在PHP方面,我有一个使用json_build_object的postgresql查询,然后我发送

echo json_encode($ nouvelle);

启动动作setNouvelle时,response.data包含以下内容:

"{"id" : 1872, "title" : "Test Title", "publication" : "2017-09-05T00:00:00", "summary" : "This is a test summary ", "category" : "admin", "content" : "<h2 style=\"text-align: justify;\">This is the test content ", "relateddisciplines" : [{"id" : 2, "name" : "Men's", "code" : "men"}, {"id" : 3, "name" : "Women's", "code" : "wen"}], "athlete" : [{"id" : 37359, "firstname" : "Reb", "lastname" : "ANDRADE", "federation" : "POR"}, {"id" : 25224, "firstname" : "Paul", "lastname" : "BULA", "federation" : "FRA"}], "events" : [{"id" : 15191, "startevent" : "2017-09-01", "endevent" : "2017-09-03", "title" : "World Cup", "city" : {"name" : "Minsk", "country" : {"code" : "BLR"}}, "status" : "approved", "hasresults" : true, "disciplines" : [{"code" : "men"}, {"code" : "wen"}]}], "keywords" : [{"id" : 40, "value" : "Women's"}, {"id" : 49, "value" : "Men's"}, {"id" : 347, "value" : "World Cup"}, {"id" : 771, "value" : "Minsk"}]}"

但是我不能使用返回数据的各个部分,例如,使用this.nouvelle.summary显示摘要

如果我尝试JSON.parse(response.data),我收到以下错误消息:

Uncaught(在promise中)SyntaxError:位置1的JSON中的意外标记o

如何设置它以便我可以使用JSON响应的各个属性

由于

编辑:

这是我的应用声明:

var app = new Vue({
http: { options: { emulateJSON: true, emulateHTTP: true }},
el: '#app',
data: {
nouvelle: {
  id : "",
  title: "",
  summary: "",
  content: "",
  category: "",
  publication: "",
  press_release: "",
  keywords: [],
  athletes: [],
  events: [],
  relateddisciplines: [],
  create_time: ""
 },
 nouvelles: [],
 modal: {
  nouvelle: {
    id : "",
    title: "",
    summary: "",
    content: "",
    category: "",
    publication: "",
    press_release: "",
    keywords: [],
    athletes: [],
    events: [],
    relateddisciplines: [],
    create_time: ""
}},
file: {},
addMode: true,
alert: {
  cls: "hidden",
  message: "",
  time: 0
}

1 个答案:

答案 0 :(得分:1)

通过更改此行来使其工作:

this.modal.nouvelle = response.data;

this.modal.nouvelle = JSON.parse(response.body.nouvelle);

没有解析正确的事情

相关问题