Ajax通过POST发送数据(JSON)

时间:2018-05-31 10:53:12

标签: javascript jquery ajax

有人可以看到为什么它显示错误超出最大调用堆栈大小?为什么不运行脚本?更新:我添加了不会将值"域"我更新了JS代码。

    function addentrys() {
    var nwentry =  {};
    el = document.getElementById('addname').value;
    eldmn = document.getElementById('adddomain').value;
    nwentry.name = el;
    nwentry.domain = eldmn;
    $.ajax({
        type: 'POST',
        url: 'api/domain',
        dataType: 'json',
        data: nwentry,
        succes: function(data) {
            alert('Ok')
        }
    })
}

PHP:

//ADD
$app->post('/domain', function () {
    $jsonContents = file_get_contents('data/data.json');
    $name = $_POST['name'];
    $domain = $_POST['domain'];
    $data = json_decode($jsonContents, true);
    $last_item = end($data);
    $last_item_id = $last_item['id'];
    $data[] = array(
        'name' => $name,
        'domain' => $domain,
        'id' => $last_item_id+1
    );
    $json = json_encode($data);
    file_put_contents('data/data.json', $json);
    return $this->response->withRedirect('../index.html');
});

3 个答案:

答案 0 :(得分:1)

function addentrys() {
    var nwentry =  {};
    el = document.getElementById('addname').value;
    nwentry.name = el;
    var data = JSON.stringify(nwentry)
    $.ajax({
        type: 'POST',
        url: 'api/domain',
        dataType: 'json',
        data: (nwentry),
        succes: function(result) {
            console.log(result)
    }
    })
}

答案 1 :(得分:1)

您将控制对象而不是值传递给ajax。尝试以下代码

    function addentrys() {
    var nwentry =  {};
    el = document.getElementById('addname')
    nwentry.name = el.value;
    var data = JSON.stringify(nwentry)
    $.ajax({
        type: 'POST',
        url: 'api/domain',
        dataType: 'json',
        data: (nwentry),
        succes: function(result) {
            console.log(result)
         }
     })
  }

答案 2 :(得分:0)

尝试以下代码。检查success功能错误并发送data可变,而非nwentry对象

function addentrys() {
var nwentry =  {};
el = document.getElementById('addname')
nwentry.name = el;
var data = JSON.stringify(nwentry)
$.ajax({
    type: 'POST',
    url: 'api/domain',
    dataType: 'json',
    data: data,
    success: function(result) {
        console.log(result)
    }
  })
}