javascript - Ajax 通过 POST 发送数据(JSON)

标签 javascript jquery ajax

有人可以看出为什么它显示错误 Maximum call stack size exceeded?为什么脚本不起作用?更新:我添加了不放置值“domain”的 php 代码,并更新了 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');
});

最佳答案

您正在将控制对象而不是值传递给 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)
         }
     })
  }

关于javascript - Ajax 通过 POST 发送数据(JSON),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50622627/

相关文章:

javascript - 在事件中播放嵌入式 API Youtube 视频

javascript - 暂时删除并稍后重新插入 DOM 元素?

javascript - rails : Foundation 5 Reveal Modal to Submit Button

javascript - Ajax GET 请求混淆

javascript - Ember js #LinkTo 标签及其行为

javascript - jQueryUI 模态对话框中的脚本只能运行一次

javascript - 从 cshtml View 调用 javascript 方法

php - 包括 file.php + id。这可以用 php 实现吗?

javascript:变量定义与函数未定义

javascript - 调用 javaScript 函数