如何将javascript数组或JSON存储到php中

时间:2017-11-16 07:59:16

标签: javascript php jquery json ajax

我有一个javaScript数组,我需要在PHP中存储,以便以后我可以将它存储到MySQL数据库。

的index.php

<form method="post">
<button type="submit" class="btn btn-default" id="php-submit" name="php-submit"><span class="glyphicon glyphicon-upload"></span></button>
<table class="table" id="table-1">
  <-- my finalArray gets generated by selecting some of these table cell values -->
</table>
</form>

app.js

$('#php-submit').click(function()
{   // For demo purpose, I have written hardcoded array values here
    var finalArray = ["Nov 2017 0:00 - 0:59", "Dec 2017 0:00 - 0:59", "Nov 2017 1:00 - 1:59", "Dec 2017 1:00 - 1:59"];
    // console.log(finalArray);
    str_json = JSON.stringify(finalArray);
    console.log(str_json);

    $.ajax({
      type: "POST",
      url: "script.php",
      data: {data : str_json}, 
      cache: false,
      success: function(){
        alert("OK");
      }
    });

    // $.post('script.php', { data: finalArray }, function (data) { 
    //  alert("OK");
    // });

});

用户点击('#php-submit')按钮后, 我想在我的script.php上显示'finalArray'或'str_json'。

以下是我尝试过的4种不同的方法。

的script.php

// approach 1: output --> blank page

   $data = json_decode(stripslashes($_POST['data']));
   foreach($data as $d){
      echo $d;
   }

// approach 2: ouptut --> null

   $data = json_decode(stripslashes($_POST['data']));
   var_dump($data);

// approach 3: output --> null

   header('Content-type: application/json; charset=utf-8');
   $json = file_get_contents('php://input');
   $json_decode = json_decode($json, true); 
   $json_encode = json_encode($json_decode);
   echo $json_encode;

// approach 4: output --> array(1) { [0]=> string(4) "null" }

   $data = $_POST['data'];
   $json_encode = json_encode($data);
   $ar = explode(',', $json_encode);
   var_dump($ar);

2 个答案:

答案 0 :(得分:4)

我认为问题在于您正在发送$.ajax请求,但正在检查浏览器标签中的script.php。要查看您需要ajax的{​​{1}}请求,请Chrome Dev Tools。像:

  1. 使用 Ctrl + Shift + I
  2. 打开Chrom开发工具
  3. 转到Network标签。 enter image description here
  4. XHR部分中查找您的请求:enter image description here
  5. 现在我运行了你的代码,它对我来说效果很好。正如你从截图中看到的那样。

    修改:而不是发送ajax请求,请尝试提交动态生成的<form>,如:

    $('#php-submit').click(function()
    {
        var finalArray = ["Nov 2017 0:00 - 0:59", "Dec 2017 0:00 - 0:59", "Nov 2017 1:00 - 1:59", "Dec 2017 1:00 - 1:59"];
        str_json = JSON.stringify(finalArray);
    
            var newForm = $('<form>', {
                'action': 'script.php',
                'target': '_top',
                'method': 'POST'
            }).append($('<input>', {
                'name': 'data',
                'value': str_json,
                'type': 'hidden'
            }));
            $(document.body).append(newForm);
            newForm.submit();
    
    });
    

    但是,如果您不想使用<form>重定向到其他网页。然后在script.php中,使用$_SESSION执行此类操作:

    if(isset($_POST['data']))
    {
        $_SESSION['data'] = json_decode(stripslashes($_POST['data']));
    }
    
    var_dump($_SESSION);
    

答案 1 :(得分:0)

不要更改app.js! 然后,您必须在script.php中输入以下代码:

namespace App\Traits;

use Illuminate\Support\Facades\Cache;

trait HasSlug {

    public function sluggable() {
        if (!$this->getSlug()) {
            $slug = $this->buildSlug();
            $this->setSlug($slug);
        }
        return $this;
    }

    public function refreshSlug() {
        $this->setSlug($this->buildSlug());
        return $this;
    }

    protected function setSlug($slug) {
        // $save_to = static::$sluggable_save_to_attribute ?? 'slug'; -- PHP bug fixed in 7.0.19 and  7.1.5
        $save_to = isset(static::$sluggable_save_to_attribute) ? static::$sluggable_save_to_attribute : 'slug';
        $this->attributes[$save_to] = $slug;
        // $this->setAttribute($save_to, $slug);
        return $this;
    }

    /**
     * @return \Eloquent
     */
    public function getSlug() {
        // $save_to = static::$sluggable_save_to_attribute ?? 'slug'; -- PHP bug fixed in 7.0.19 and  7.1.5
        $save_to = isset(static::$sluggable_save_to_attribute) ? static::$sluggable_save_to_attribute : 'slug';
        // return $this->getAttribute($save_to);
        return $this->$save_to;
    }

    /**
     * @return string
     */
    protected static function getRand() {
        $length = 11;
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $size = strlen($chars);
        $str = '';
        for ($i = 0; $i < $length; $i++) {
            $str .= $chars[rand(0, $size - 1)];
        }
        return $str;
    }

    /**
     * @param string $str;
     * @return string;
     */
    protected function mod($str) {
        // if (static::$sluggable_uppercase ?? false ) {  -- PHP bug fixed in 7.0.19 and  7.1.5
        $uppercase = isset(static::$sluggable_uppercase) ? static::$sluggable_uppercase : false;
        if ( $uppercase ) {
            return strtoupper($str);
        } else {
            return $str;
        }
    }

    /**
     * @return string
     */
    protected function buildSlug() {
        // $attr = static::$sluggable_build_from_attribute ?? 'title'; -- PHP bug fixed in 7.0.19 and  7.1.5
        $attr = isset(static::$sluggable_build_from_attribute) ? static::$sluggable_build_from_attribute : 'title';
        $string = $attr && $this->$attr ? $this->$attr : static::getRand();
        return $this->bestSlugFrom($string);
    }

    /**
     * @param string $string
     * @return string
     */
    public function bestSlugFrom($string) {
        $original = $slug = $this->mod(static::sluggify($string));
        $i = 1;
        while (static::findBySlug($slug, true)) {
            $slug = $original . '-' . $i;
            $i++;
        }
        return $slug;
    }

    /**
     * Sluggify a string
     * @param string $text
     * @return string
     */
    public static function sluggify($text) {
        $text = str_replace(array('#', 'ω'), array(' sharp', ' omega'), $text); // replace non letter or digits by -
        return str_slug($text);
    }

    /**
     * Get a model by the slug
     * @param string $slug
     * @param bool $includeTrashed
     * @return static
     */
    public static function findBySlug($slug, $includeTrashed = false ) {
        // $slugAttr = static::$sluggable_save_to_attribute ?? 'slug'; -- PHP bug fixed in 7.0.19 and  7.1.5
        $slugAttr = isset(static::$sluggable_save_to_attribute) ? static::$sluggable_save_to_attribute : 'slug';
        return Cache::remember( get_called_class() . "_bySlug_{$slug}_{$includeTrashed}", 1, function () use ($slug, $includeTrashed, $slugAttr) {
            $q = static::where($slugAttr ?? 'slug', $slug);
            if ( $includeTrashed && method_exists(get_called_class(), 'bootSoftDeletingTrait') ) {
                /* Make sure the model has soft deletes before calling this method */
                $q->withTrashed();
            }
            return $q->first();
        });
    }

}

希望它能帮到你!